eqiz eqiz - 11 months ago 37
PHP Question

Why can't I access my static variables from another php page

I'm trying to create a simple class that holds all my session information so I can easily obtain it later on. I don't like having to keep using $_SESSION['foo'] to access it through all my PHP pages because I want to be better organized and have all of the session data stored in one area so I can just pull up the page if I need a quick reference to see all the variables I've stored. Also on a side note, if there is a better way I'm suppose to store SESSION data so that its organized and easily read by other programmers that would be very helpful information as well.

So far I created the following class..

class staticVars {

public static $ownerID;
public static $ownerFullName;
public static $ownerEmail;

public static function createFromArray($array) {
$ownerID = $array['ownerID'];
$ownerFullName = $array['ownerFullName'];
$ownerEmail = $array['ownerEmail'];

in my PHP page I have this...



echo ("owner id " . staticVars::$ownerID);

However, when I echo out the response, the $ownerID just comes back blank.

Answer Source

You're setting variables local to the function and not the class variables. Use self or maybe static:

public static function createFromArray($array) {
    self::$ownerID = $array['ownerID'];
    self::$ownerFullName = $array['ownerFullName'];
    self::$ownerEmail = $array['ownerEmail'];

See: Late Static Bindings for when you would use static.