Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically call a static variable (array)

Here's my question for today. I'm building (for fun) a simple templating engine. The basic idea is that I have a tag like this {blog:content} and I break it in a method and a action. The problem is when I want to call a static variable dynamically, I get the following error .

Parse error: parse error, expecting `','' or `';''

And the code:

 $class = 'Blog';
 $action = 'content';
 echo $class::$template[$action];

$template is a public static variable(array) inside my class, and is the one I want to retreive.

like image 708
BebliucGeorge Avatar asked Dec 04 '22 14:12

BebliucGeorge


2 Answers

What about get_class_vars ?

class Blog {
    public static $template = array('content' => 'doodle');
}

Blog::$template['content'] = 'bubble';

$class = 'Blog';
$action = 'content';
$values = get_class_vars($class);

echo $values['template'][$action];

Will output 'bubble'

like image 77
Kuroki Kaze Avatar answered Dec 27 '22 07:12

Kuroki Kaze


You may want to save a reference to the static array first.

class Test
{
    public static $foo = array('x' => 'y');
}

$class  = 'Test';
$action = 'x';

$arr = &$class::$foo;
echo $arr[$action];

Sorry for all the editing ...

EDIT

echo $class::$foo[$action];

Seems to work just fine in PHP 5.3. Ahh, "Dynamic access to static methods is now possible" was added in PHP 5.3

like image 20
Philippe Gerber Avatar answered Dec 27 '22 09:12

Philippe Gerber