1

Consider under my cpp\controllers\ I've 5 files like (AController.php, BController.php etc..)

Each controller has its own public variable like this..

AController.php   --- public $variable='Testing';
BController.php   --- public $variable='Bhuvanesh';

From my app\views\main.php

If A controller is called I need the value Testing. If B controller is called I need Bhuvanesh.

Its possible in yii2? Thanks in advance.

3 Answers 3

4

You should read Yii2 Views Guide :

within the view you can get the controller object by the expression $this->context

So, you should simply use this in your view :

$this->context->variable
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you create a getter method with same name?

class AController {
     public function getVariable() { return 'A'; }
}

class BController {
     public function getVariable() { return 'B'; }
}

class CController {
     public function getVariable() { return 'C'; }
}

Then you can call with

$controller->variable

3 Comments

For your answer, I have to add the controller classes in layout. I have 50 services to do.. So I planned to create the 50 controllers.. Then I have to add the 50 classes in my layout.
You could handle this issue in a BaseController. Create a public function getVariable() in BaseController (of each subcontroller) and based on get_class($this) inside the getVariable() you can return different function response.
then you can call with $controller->getVariable(); not ->variable if he uses the __construct he gets the echo instantly instead of needing to call it :) __construct is basic OOP so i recommend doing that.
0

You could use the __construct() magic method? this function gets executed right when the class is used. If you make something like

public function __construct(){
    echo $this->var; //echo out whatever you want here.
}

That's how i would do it.

1 Comment

in your controller. @Bhuvanesh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.