简体   繁体   中英

How come it is possible to access variables without $this in the view?

I started working with Zend Framework 2 a short while ago.

In the controller, I am sending variables to view using

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

In the view I was doing:

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

and then using those variable directly so I don't have to go through $this each time I use them.

I was working on it, and was modified a few stuff, and while I wanted to debug, I removed those two previous lines hoping it would break.

To my surprise, the $exampleVariable and $exampleVariable2 were still available. At first, I thought it was a caching problem, but it turns out all the array keys that are sent to the view with SetVariables() can be accessed as variables.

My question is, how come it is possible to access them without $this ?

I am probably gonna be warned about this, but this question if just for curiosity. I won't use the variables directly, as I prefer to create them in the view so I can comment them and add their respective variable types and stuff.

If you take a look at the PHPRenderer class, specifically PHPRendered::render()

Zend\View\Renderer\PHPRenderer 

You will see how the Views are generated, using extract ( http://php.net/extract )

This allows any of the views variables to be accessed locally inside the view / template.

Take a look here

Variables assigned to the view – either via a View Model, Variables container, or simply by passing an array of variables to render()– may be retrieved in three ways:

  • Explicitly, by retrieving them from the Variables container composed in the PhpRenderer: $this->vars()->varname.
  • As instance properties of the PhpRenderer instance: $this->varname. (In this situation, instance property access is simply proxying to the composed Variables instance.)
  • As local PHP variables: $varname. The PhpRenderer extracts the members of the Variables container locally.

The explanation:

The PhpRenderer uses extract function to extract the variables into the function (render) scope. This allows to use $exampleVariable in the template. Further the PhpRenderer uses the magic __get function. So if you call $this->exampleVariable it looks in the data array directly.

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