简体   繁体   中英

Php Yii2 How can i access the variables declared in layouts to site?

I'm developing web application in php Yii2. I have a variable in layouts/header.php

I want to access it in site/index.php

My code: (layouts/header.php)

switch ($sub_ext) {
    case "ksa":
        $cvalue = array_diff( $country_array, array("Saudi Arabia") );
        $avalue = "Saudi Arabia";
        break;
    case "kuwait":
        $cvalue = array_diff( $country_array, array("Kuwait") );
        $avalue = "Kuwait";
        break;
    default:
        $cvalue = array_diff( $country_array, array("UAE") );
        $avalue = "UAE";
}

I want to display the $avalue variable in site/index.php

My code in (site/index.php):

<?php echo $avalue; ?>

I'm getting nothing displayed here.

Your variable is in layouts/header.php and if you want to access it in site/index.php then you should pass that variable to this view (site/index.php)

or the other option is to use sessions.

You can't pass a variable from layout to view. That's because the view is rendered first and the layout is rendered after the view.

If you have some property that you need to access in multiple places you need to do it some other way.

1) You can wrap it in some custom component then access it through component. You can put the logic that sets the variable into the init() method. Then you can use the component through DI container. See the article about components.

2) You can make a static helper class that will return proper value.

3) You can use some event or callback to set the variables in view's params property. That way it will be available in every view/layout in $this->params array. You can use for example the beforeAction() callback in controller or its beforeAction event . In beforeAction callback you can access the params property with $this->view->params from elsewhere you might need to use Yii::$app->view->params .

you need to add this code to your case statements, and default

$this->render('index.php',array('avalue'=>$avalue));

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