Ever had a class with data in it and needed to be able to access that data from anywhere in your project? Should be simple enough to pull off, but anyone who has tried would quickly find that is not so. I offer a simple solution to storing universally accessible data for your application.
The Solution
Oddly enough, the solution utilizes storing static data in a function. Which, then at a later time can be accessed, changed, or simply removed. The great thing about using a regular old function is that you can access it anywhere in your application at anytime.
function config($set=NULL)
{
static $data;
if($set!==NULL)
{
$data = $set;
}
return $data;
}
And to store something in the function you just have to do this:
config('My data');
Accessing that data is just as easy.
echo config();
Even Better Storage
Alternatively, you can easily store an object in the function.
// Create the class
class something
{
public function message()
{
echo 'Hello, World';
}
}
// Now store it in our function
config(new something);
// Add stuff to the object
config()->test = 'wow';
config()->another = 'sweet';
echo '<pre>';
// Display all of the object
print_r(config());
// Use function in object
config()->message();
echo '</pre>';
Comment
See what others have to say on this topic, or add your own two cents.