我正在阅读一些关于 zend 框架的教程和文档,在我遇到 $this
之前,大多数事情都是有意义的/application/layout/scripts/layout.phtml
中的变量, 有人提到 $this
是在引导过程中创建的 View 对象的一个实例。
据我所知,您不能使用 $this
作为变量名 因为 $this
是 php 的保留关键字,用于在类上下文中引用相同的对象。任何将其用作变量的尝试都将导致 fatal error 并显示以下错误消息 Fatal error: Cannot re-assign $this
并根据作者的陈述 There is a variable, $this, available which is an instance of the view object
,我无法理解这背后的理论。怎么来的$this
是在类之外使用的吗?
最佳答案
它实际上是在对象的上下文中使用的。你应该自己看看代码,但是 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;
}
Zend Framework 做得更复杂一些,因此它比那更灵活一些,但这是基本思想。
然后,在 viewScript 内部,从技术上讲,它位于 render() 方法内部,就好像代码确实位于“include ...”位置。 (过于简单化,但总体思路成立。)
关于php - Zend Layout 中的 $this 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552826/