For all my practice with OOP I have never used $this outside of the class definition.
While in zendframework we use $this in view template files, obviously it is not the scope of a class definition. I wonder how it has been implemented ?
I have googled a lot but got no luck.
I want to know the mechanism how zendframework renders it's view files with $this.
It actually is in the scope of a class definition. Simple test-case:
<?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( );
Now, create another file:
<?php
// let's call this my-view.php.
<h1>Private variable: <?php echo $this->variable; ?></h1>
Now go and visit view.php, and you will see that my-view.php had access to the private variable of the View class. By using include
, you actually load the PHP file into the current scope.
In view script files (.phtml
ones) $this
refers to the currently used instance of Zend_View
class - the one that is ordered to render this particular script. Quoting the doc:
This is [a view script]
a PHP script like any other, with one
exception: it executes inside the scope of the Zend_View instance,
which means that references to $this point to the Zend_View instance
properties and methods. (Variables assigned to the instance by the
controller are public properties of the Zend_View instance).
And this it how it's done: when your controller calls (explicitly or implicitly) render
method (defined in Zend_View_Abstract
class), the following method (defined in Zend_View
class) is executed in the end:
/**
* 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);
}
}
... where func_get_arg(0)
refers to the full filename (path + name) of the included script.