在Zend Layout中使用$ this变量

Ibr*_*mar 3 php zend-framework

我正在阅读有关zend框架的一些教程和文档,大多数事情都有意义,直到我遇到$this变量/application/layout/scripts/layout.phtml,它被提到$this是在引导期间创建的视图对象的实例.

据我所知,你不能$this用作变量名,因为$this是php的保留关键字,用于引用类上下文中的同一个对象.任何将它用作变量的尝试都将导致致命错误,并出现以下错误消息,Fatal error: Cannot re-assign $this并且根据作者的陈述There is a variable, $this, available which is an instance of the view object,我无法理解这背后的理论.为什么要$this在课堂上下文中使用?

Cor*_*bin 6

它实际上是在对象的上下文中使用的.您应该自己查看代码,但是render()背后的基本思想(代理的toString方法):

public function render()
{
    //Start output buffering
    ob_start();
    include $this->viewScript;
    //Get the content from the include
    $content = ob_get_flush();
    return $content;
}
Run Code Online (Sandbox Code Playgroud)

Zend Framework做得更复杂一些,因此它比这更灵活,但它是基本的想法.

然后,在viewScript内部,它在技术上是在render()方法内部,就像代码实际上在"include ..."位置一样.(过度简化,但总体思路仍然存在.)