PHP定义包含文件的范围

Pim*_*ger 4 php scope include

我有很多PHP视图文件,我曾经使用简单的include语句将其包含在我的控制器中.它们都使用在视图类中声明的方法,它们就像$ view-> method(); 但是我最近决定,如果包含也可以通过这个视图类来完成.但是,这会更改包含文件的范围,以便不再定义$ view.这是一个代码示例:

in someViewFile.php (BOTH siuations)
    <html>
    <head><title><?php echo $view->getAppTitle(); ?></title>
    etc.
OLD SITUATION in controller:
    $view = new view;
    include('someViewFile.php'); //$view is defined in someViewFile.php
NEW SITUATION in controller:
    $view = new view;
    $view->show('someViewFile'); //$view is not defined in someViewFile.php
Run Code Online (Sandbox Code Playgroud)

现在我在视图类中使用它来解决问题:

public function show($file){
    $view = &$this;
    include($file.".php");
}
Run Code Online (Sandbox Code Playgroud)

是否有声明包含文件的范围或这是解决问题的最佳方法?

这些例子是粗略简化的.

meo*_*ouw 12

这是一个简化但功能强大的视图类,我已经看过很多并使用了很多.
正如您在下面的代码中看到的那样:使用模板文件的文件名实例化视图.
客户端代码(可能是控制器)可以将数据发送到视图中.此数据可以是您甚至其他视图所需的任何类型.
渲染父级时,将自动呈现嵌套视图.
希望这可以帮助.

// simple view class
class View {
    protected $filename;
    protected $data;

    function __construct( $filename ) {
        $this->filename = $filename;
    }

    function escape( $str ) {
        return htmlspecialchars( $str ); //for example
    }

    function __get( $name ) {
        if( isset( $this->data[$name] ) {
            return $this->data[$name];
        }
        return false;
    }

    function __set( $name, $value ) {
        $this->data[$name] = $value;
    }

    function render( $print = true ) {
        ob_start();
        include( $this->filename );
        $rendered = ob_get_clean();
        if( $print ) {
            echo $rendered;
            return;
        }
        return $rendered;
    }

    function __toString() {
        return $this->render();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

// usage
$view = new View( 'template.phtml' );
$view->title = 'My Title';
$view->text = 'Some text';

$nav = new View( 'nav.phtml' );
$nav->links = array( 'http://www.google.com' => 'Google', 'http://www.yahoo.com' => 'Yahoo' );

$view->nav = $nav;

echo $view;
Run Code Online (Sandbox Code Playgroud)

模板

//template.phtml
<html>
    <head>
        <title><?php echo $this->title ?></title>
    </head>
    <body>
        <?php echo $this->nav ?>
        <?php echo $this->escape( $this->text ) ?>
    </body>
</html>

//nav.phtml
<?php foreach( $this->links as $url => $link ): ?>
    <a href="<?php echo $url ?>"><?php echo $link ?></a> 
<?php endforeach ?>
Run Code Online (Sandbox Code Playgroud)


cha*_*aos 3

您无法更改 include() 范围,不,因此您的方法可能与您所描述的情况一样好。尽管我自己会跳过丑陋的 PHP4 兼容 & 符号。