【问题标题】:How come it is possible to access variables without $this in the view?为什么视图中没有 $this 就可以访问变量?
【发布时间】:2013-08-13 10:00:56
【问题描述】:

不久前我开始使用 Zend Framework 2。

在控制器中,我发送变量以查看使用

    return $viewmodel->setVariables(array(
                'exampleVariable' => 'exampleValue', 
                'exampleVariable2' => array(
                    'variableInArray' => $this->getMacAddress(),
                ),
    ));

在我正在做的视图中:

$exampleVariable = $this->exampleVariable
// and 
$exampleVariable2 = $this->exampleVariable2

然后直接使用这些变量,这样我每次使用它们时都不必经过$this

我正在研究它,并修改了一些东西,当我想调试时,我删除了前两行,希望它会中断。

令我惊讶的是,$exampleVariable$exampleVariable2 仍然可用。一开始以为是缓存问题,结果发现所有用SetVariables()发送到视图的数组键都可以作为变量访问。

我的问题是,没有$this,怎么可能访问它们?

我可能会收到警告,但这个问题只是出于好奇。我不会直接使用变量,因为我更喜欢在视图中创建它们,这样我就可以评论它们并添加它们各自的变量类型和内容。

【问题讨论】:

    标签: php templates zend-framework2 scope


    【解决方案1】:

    看看here

    分配给视图的变量——通过视图模型、变量容器,或者只是通过将变量数组传递给 render()——可以通过三种方式检索:

    • 明确地,通过从 PhpRenderer 中组成的变量容器中检索它们:$this->vars()->varname。
    • 作为 PhpRenderer 实例的实例属性:$this->varname。 (在这种情况下,实例属性访问只是代理到组合的变量实例。)
    • 作为本地 PHP 变量:$varname。 PhpRenderer 在本地提取变量容器的成员。

    解释:

    PhpRenderer 使用extract 函数将变量提取到函数(渲染)范围内。这允许在模板中使用$exampleVariable。此外,PhpRenderer 使用神奇的__get 函数。因此,如果您调用$this->exampleVariable,它会直接在数据数组中查找。

    【讨论】:

      【解决方案2】:

      如果你看一下 PHPRenderer 类,特别是 PHPRendered::render()

      Zend\View\Renderer\PHPRenderer 
      

      您将看到如何使用提取 (http://php.net/extract) 生成视图

      这允许在视图/模板中本地访问任何视图变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-31
        相关资源
        最近更新 更多