简体   繁体   中英

Basic Yii Concept: Where is $this defined?

I'm taking a look at Yii Framework's tutorial about a blog application. I'm in the process of understanding, but I don't understand one major component: this is found in the beginning of a particular .php view file.

<?php
$this->breadcrumbs=array(
    'Manage Posts',
);
?>

I'd just like to know where does $this come from. As far as I understand, $this can only be used if it is within the scope of a class. However, I see no class implemented here, so can anyone enlighten me on how Yii does this for me?

$this here refers to the current controller class. If you see the controller in components/Controller.php , you'll also see a $breadCrumbs=array(); . See definitive guide to views :

Inside the view script, we can access the controller instance using $this . We can thus pull in any property of the controller by evaluating $this->propertyName in the view.

The controller renders a view ultimately using, renderInternal . And if you see the source of that function, you'll see php's require() :

public function renderInternal($_viewFile_,$_data_=null,$_return_=false)
{
    // we use special variable names here to avoid conflict when extracting data
    if(is_array($_data_))
        extract($_data_,EXTR_PREFIX_SAME,'data');
    else
        $data=$_data_;
    if($_return_)
    {
        ob_start();
        ob_implicit_flush(false);
        require($_viewFile_);
        return ob_get_clean();
    }
    else
        require($_viewFile_);
}

And because require is used, $this is available at that point to the code being included:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Hence when we do $this->render('view'); the view will have access to $ this .

I'm pretty sure Yii compiles templates into classes, so at runtime you actually do have a class. Check __FILE__ and get_class($this) for details.

If this template is just require d inside a method, it actually goes into object scope. So this stands for some View object that renderes the temlate.

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