對於我所有使用OOP的練習,我從未在類定義之外使用過$。
在zendframework中,我們在視圖模板文件中使用$ this,顯然它不是類定義的範圍。我想知道它是如何實施的? 我搜索了很多,但沒有運氣。
我想知道zendframework如何使用$ this來呈現它的視圖文件的機制。
對於我所有使用OOP的練習,我從未在類定義之外使用過$。
在zendframework中,我們在視圖模板文件中使用$ this,顯然它不是類定義的範圍。我想知道它是如何實施的? 我搜索了很多,但沒有運氣。
我想知道zendframework如何使用$ this來呈現它的視圖文件的機制。
它實際上是在類定義的範圍內。簡單的測試案例:
<?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,你會看到我的-view.php曾獲得的私有變量View類。通過使用include
,您實際上將PHP文件加載到當前作用域中。
不錯的一個解釋..謝謝很多 –
鑑於腳本文件(.phtml
的)$this
指Zend_View
類的當前使用的實例 - 即下令渲染這個特殊的腳本之一。引用the doc:
這是
[a view script]
PHP腳本像任何其他的,有一個 例外:它執行的Zend_View實例的範圍內, 這意味着在Zend_View的實例$至此引用 性能和內部方法。 (由 控制器分配給實例的變量是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);
}
}
:當你的控制器來電(或明或暗地)
render
方法(在
Zend_View_Abstract
類中定義),下面的方法(在
Zend_View
類中定義)到底是執行
...其中func_get_arg(0)
引用包含腳本的完整文件名(路徑+名稱)。
得到了點謝謝你的答案 –
實際上,它不在類定義之外使用。 'var_dump($ this);'表明它是類'Zend_View'的實例。 – Leri