I'd like to create a global variable in CakePHP. If I define something in in my app_controller.php like
var $varName
I can access
$this->varName
from any of my controllers, but I cannot get to it from models.
How can I create a global variable accessible from the models?
The value of $varName isn't known until runtime, so I don't think bootstrap.php is an option.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
Just create a library file and create fields for globals you need there. Import this library everywhere you need access to these fields. create a singleton in the globals library (see How do you build a Singleton in Dart? for more details).
CakePHP’s new Configure class can be used to store and retrieve application or runtime specific values. Be careful, this class allows you to store anything in it, then use it in any other part of your code
To save global variables use the Configure Class. For example:
Configure::write('Company.name','Pizza, Inc.');
To read the variable later in any place of your code use:
Configure::read('Company.name'); //yields: 'Pizza, Inc.'
The recommended file to store global constants is in app/config/bootstrap.php
For more information see:
Configure class - Configure Class CakePhp. or Section 3.4.7 on Bootstrapping
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With