3

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

2
  • 1
    you need to explain more what it is used for. otherwise one can only guess. and in general Configure is a very easy and clean way to do that, yes. Commented Sep 28, 2012 at 11:20
  • Just want to share some variables with more than one function. Something like $isOwner, or $isAdmin. Commented Sep 28, 2012 at 11:23

1 Answer 1

18

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why is it in the index function? Wouldn't it be in the beforeFilter one?
its just an example, should be accesible anywhere in any controller.
Ok, thanks, but i not use it as the variables read info from models and cake doesn't allow many calls on there.

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.