Need to share global variables throughout your app?

Posted by Felix Geisendörfer, on Jun 11, 2006 - in PHP & CakePHP » Core & Hacking

Deprecated post

The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.

Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.

Comments: You can continue to leave comments on this post, but please consult Google or our search first if you want to get an answer ; ).

I just came into a situation where I needed to share a global variable throughout my cakephp app, and I think I found a great way to accomplish it. CakePHP has a cool little class called Configure that is used to store path's to controllers, models and views. The interesting thing is, that you can use it for you personal needs as well. Simply do this somewhere in your app (even works in bootstrap.php):

php
  1. $config =& Configure::getInstance();
  2. $config->myVariable = 'Hello World';

Now you can access myVariable anywaywhere inside your application by doing:

php
  1. $config =& Configure::getInstance();
  2. debug($config->myVariable);

I like this method way better then the php 'global' keyword which seems pretty messy to me. I'm also a big fan of this Class::getInstance() pattern that is used throughout cakephp - really neat!

Anyway, don't make more use of this then neccessary, because CakePHP has a really good (mvc) convention about what should be accessible from where and it's a good idea to stick with it.

--Felix Geisendörfer aka the_undefined