Page 1 of 1

Using dynamic class name to access static vars

Posted: Sat Jul 04, 2009 10:20 am
by ben.artiss
Hi everyone,

I'm making a 'recall' function that restores a session variable into a static variable of a dynamic class name, but I've hit a roadblock with the T_PAAMAYIM_NEKUDOTAYIM error. Here's an example of how it worked before I tried with the dynamic class name:

Code: Select all

class foo {
    public static $var1, $var2;
 
    public function __construct() {
        $this->recall('var1'); // Restores value of $_SESSION['var1'] into foo::$var1
        $this->recall('var2',true); // 2nd option auto-unset's the associated session var
    }
 
    private function recall($var,$autounset=false) {
        if (!isset($_SESSION[$var])) {
            return false;
        }
 
        foo::${$var} = $_SESSION[$var];
 
        if ($autounset) {
            unset($_SESSION[$var]);
        }
 
        return true;
    }
}
Here's what I've done to break it:

Code: Select all

class foo {
    public static $var1, $var2;
 
    public function __construct() {
        $this->recall('foo','var1');
        $this->recall('foo','var2',true);
    }
 
    private function recall($class,$var,$autounset=false) {
        if (!isset($_SESSION[$var])) {
            return false;
        }
 
        /*
            Because $var works to access a public var, and ${$var} works to
            access a static var, I figured $class would work...
        */
        $class::${$var} = $_SESSION[$var];
 
        if ($autounset) {
            unset($_SESSION[$var]);
        }
 
        return true;
    }
}
... which spews the parse error about the T_PAAMAYIM_NEKUDOTAYIM (::). The reason I want it to accept a class name is so I can use the same function from within other classes, without copy and pasting the code into each file. Does anyone know a correction to the syntax I'm using?

Thanks in advance, Ben

[SOLVED] Re: Using dynamic class name to access static vars

Posted: Sat Jul 04, 2009 11:16 am
by ben.artiss
I found the answer if anyone happens to need it, the key was eval()...

Code: Select all

class foo {
    public static $var1, $var2;
 
    public function __construct() {
        foo::recall('foo','var1');
        foo::recall('foo','var2',true);
    }
 
    private function recall($class,$var,$autounset=false) {
        if (!isset($_SESSION[$var])) {
            return false;
        }
 
        eval($class.'::${$var} = $_SESSION[$var];');
 
        if ($autounset) {
            unset($_SESSION[$var]);
        }
 
        return true;
    }
}