1

对于我所有的 OOP 实践,我从来没有在类定义之外使用过 $this。

虽然在 zendframework 中我们在视图模板文件中使用 $this,但显然它不是类定义的范围。我想知道它是如何实施的?我用谷歌搜索了很多,但没有运气。

我想知道 zendframework 如何使用 $this 呈现它的视图文件的机制。

4

2 回答 2

10

在视图中,脚本文件(.phtmlones)$this指的是当前使用的Zend_View类实例——被命令渲染这个特定脚本的实例。引用文档

这是[a view script]一个与其他任何脚本一样的 PHP 脚本,但有一个例外:它在 Zend_View 实例的范围内执行,这意味着对 $this 的引用指向 Zend_View 实例的属性和方法。(控制器分配给实例的变量是 Zend_View 实例的公共属性)。

这就是它的完成方式:当您的控制器调用(显式或隐式)render方法(在Zend_View_Abstract类中定义)时,最后执行以下方法(在类中定义Zend_View):

/**
 * Includes the view script in a scope with only public $this variables.
 *
 * @param string The view script to execute.
 */
protected function _run()
{
   if ($this->_useViewStream && $this->useStreamWrapper()) {
      include 'zend.view://' . func_get_arg(0);
   } else {
      include func_get_arg(0);
   }
}

... 其中func_get_arg(0)指的是包含脚本的完整文件名(路径 + 名称)。

于 2012-12-12T12:59:51.313 回答
3

它实际上在类定义的范围内。简单的测试用例:

<?php
// let's call this view.php
class View {
   private $variable = 'value';
   public function render( ) {
       ob_start( );
       include 'my-view.php';
       $content = ob_get_clean( );
       return $content;
   }
}
$view = new View;
echo $view->render( );

现在,创建另一个文件:

<?php
// let's call this my-view.php.
<h1>Private variable: <?php echo $this->variable; ?></h1>

现在去访问view.php,你会看到my-view.php 可以访问View 类的私有变量。通过使用include,您实际上将 PHP 文件加载到当前作用域中。

于 2012-12-12T13:01:23.737 回答