php - Zend Layout 中的 $this 变量

标签 php zend-framework

我正在阅读一些关于 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/

相关文章:

php - Codeigniter flashdata - 我是否正确使用它?

php - 使用 php 和 pdo 插入的表单

php - 为什么我的 post 方法在 Laravel 中不起作用?

php - 如何将查询的值分配给 zend 中的变量

php - 在 Zend Framework 中转义字段名称中的点

php - 从 htdocs 外部运行我的 php 文件

php - 检查2个表中是否存在数据

php - 帮助使用 DRY 原则在服务类中创建灵活的基础 'find' 方法

php - 使用 Zend Framework 和 PHP 发送电子邮件

php - 在 Zend 模型中实现 PostgreSQL 数组