Global variable in controller cakephp 2

Alvaro picture Alvaro · Sep 28, 2012 · Viewed 14.9k times · Source

What's the way to have a global variable inside a controller?

I have tried to do it using beforeFilter but it is not accessible from the others functions.

Can it only be done using Configure::read and Configure::write

Answer

thanat picture thanat · Sep 28, 2012

you can set variable accessible in any controller in your AppController

class AppController extends Controller {
    public $myGlobalVar;  

    public function beforeFilter()
    {
         //this can be anything array, object, string, etc .....
         $this->myGlobalVar = "test2";
    }
 }

then in your other controller you can access variable anywhere like this

class TestController extends AppController {

    public function index() {

        debug($this->myGlobalVar);
    }
}