PHP class to manage session variables
A simple class enabling you to:
- Avoid typos in session variable names
- Initialise session variables so they are always valid
- Control what variable names are in use and document them
- Stop them pesky apostrophes from spoiling your SQL and <input>s by swapping with backticks
To use, for example, extend like this:
<?php
class Session extends m3Session
{
public function __construct()
{
parent::__construct();
$this->init('cart'); // User starts with an empty shopping cart
$this->init('timestamp_entry', time()); // Record when user first entered site
}
}
?>
then employ...
<?php
Session::pre_construct(); // Must be called before any output is echoed
$session = new Session;
echo "Unix time stamp you entered site = $session->timestamp_entry";
$session->cart = 17; // Same as $_SESSION['cart']=17;
$session->forename = 'Alan'; // Error. No such session var !
?>
And here is the class
<?php
class m3Session
{
private static $pre_constructed = false;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public static function pre_construct()
{
session_start();
self::pre_constructed = true;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public function __construct()
{
if (!self::pre_constructed)
{
trigger_error("m3Session requires pre-construction", E_USER_ERROR);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public function __get($name)
{
$name = strtolower($name);
if (!array_key_exists($name, $_SESSION))
{
trigger_error("m3Session::$name is not a gettable property", E_USER_ERROR);
return;
}
return $_SESSION[$name];
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public function __set($name, $value)
{
if (!array_key_exists($name, $_SESSION))
{
trigger_error("m3Session::$name is not a settable property", E_USER_ERROR);
return;
}
$value = str_replace("'", "`", $value);
$_SESSION[$name] = $value;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected function init($name, $value = '')
{
if (!array_key_exists($name, $_SESSION))
{
$_SESSION[]=$value;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
?>