Yes, let's be very clear. An application variable is not a session variable. It is a globally set value.
I have seen this question so many times, (http://www.zend.com/phorum/list.php?num=6&thread=69&action=-1&) and it really is no problem at all. Simply put: you want to be able to set a variable/array/object from one instance of a script, and have it readable by other script instances. An application variable is just a nice way of saying "hey, we're saving this information over here, and you can all see it". Save a file, set a shared memory key, put it in a database, whatever! The point is it can be done.
But the convenience of a quick front end to that functionality is nice, so without further ado, here is my basic implementation (it can be extended in many ways):
--------class.Application.php ---------
<?php
/ Application class, includes methods to
get/set application variables by
storing serialized values to tempfiles /
class Application
{
function setVar($varname,$value)
{
//$temp_path = 'C:\TEMP\'; // for Windows server
$temp_path = '/tmp/'; // for Unix server
$strvalue = serialize($value);
// generate a storeable representation of
// the value, with it's type and structure
$file_pointer = fopen($temp_path . $varname, 'w');
if(!(fwrite($file_pointer,$strvalue)))
{
return false; //success
}
else
{
return true; //not able to write file
}
} //end function setVar
function getVar($varname)
{
//$temp_path = 'C:\TEMP\\'; // for Windows server
$temp_path = '/tmp/'; // for Unix server
// file(path) returns an array, so we implode it
if(!($strvalue = implode("",file($temp_path . $varname))))
{
return false; //could not get file
}
else
{
$value = unserialize($strvalue);
return $value; //here's the value of the variable
}
} //end function getVar
} //end class Application
?>
----------- end class.Application.php ------
Now, all you have to do is make this file part of your standard include set, or define it's path in the auto_prepend_file directive in php.ini. Then, anywhere you want, you can simply do something like "Application::setVar("varname",$value_or_object);". Then, on any other page, just do
$my_var_or_obj = Application::getVar("varname");
Or, for error checking:
if(!Application::setVar("varname",$value_or_object)
{
echo "Could not save application var!";
exit;
}
else
{
echo "Saved \$varname as application variable.";
}
You can see that my "backend" for this is fairly simple at the moment--just saving flat files. But depending on your system, you can do different things for storage, without affecting the function syntax at all. For example, save the value in a database, or store it in shared memory, so it can be more quickly accessed. Also, in a server cluster, you could save the value to a shared network directory, or a shared database, so that other servers can read the value.