Using dynamic class name to access static vars
Posted: Sat Jul 04, 2009 10:20 am
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:
Here's what I've done to break it:
... 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
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;
}
}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;
}
}Thanks in advance, Ben