I am working on a PHP system where I need to have a couple of variables constantly set throughout all classes used. Data is mostly retrieved through ajax calls and MySQL queries.
The value of each variable will not change unless a specific link is clicked.
What is the best method to achieve this? I am a bit stuck because I can use neither global variables, nor a cookie.
Thanks in advance.
N.
You should look into sessions.
Here is a simple example of using session:
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
Some html later on ...
<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>
<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>
Store it in a super class then. So all subclasses derived from the super class can access this variable that is neither global nor a session variable.
<?
class MySuperClass
{
protected myVariable;
}
class MySubClass extends MySuperClass
{
function bleh()
{
$this->myVariable = "yeah... neither global or cookie";
}
}
?>
// Or use $_SESSION instead of the above. $_SESSION['mynamespace']['my_variable'];
session_start();
echo $_SESSION['foo'];
$_SESSION['foo'] = $_REQUEST['foo'];
You could use a registry. But think carefully whether you really need to do this and think about dependency injection. Try and make your code loosely coupled.