简体   繁体   中英

$this variable in Zend Layout

I was going through some tutorial and documentation about zend framework, most of things made sense until i came across $this variable in /application/layout/scripts/layout.phtml , it was mentioned that $this is an instance of the view object that was created during bootstrapping.

to my knowledge you cannot use $this as the variable name as because $this is a reserved keyword for php used to refer the same object within the class context. any attempt to use it as a variable will result in Fatal error with the following error message Fatal error: Cannot re-assign $this and as per the author's statement There is a variable, $this, available which is an instance of the view object , i am unable to understand the theory behind this. how come $this is being used out of the class context?

It's actually being used in the context of an object. You should look at the code yourself, but the basic idea behind render() (which is the toString method by proxy):

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 does it a bit more complexly so that it's a bit more flexible than that, but it's the basic idea.

Then, inside of the viewScript, it's technically inside of the render() method just as if the code were literally in that "include ..." place. (Oversimplifying that, but the general idea holds.)

It's probably being used in the class context. Imagine the view being created along the following lines:

class View {

  public function render($viewfile = 'views/myviewfile.phtml') {
    ob_start();
      include($viewfile);
      $view_data = ob_get_contents();
    ob_end_clean();

    echo $view_data;
  }
}

The view presentation process is probably more complex than simply capturing an include d view file, but you can see how $this would be available to the view when View::render() is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM