Dynamically call a static variable (array)

12,477

Solution 1

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'

Solution 2

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

Share:
12,477
BebliucGeorge
Author by

BebliucGeorge

Updated on June 08, 2022

Comments

  • BebliucGeorge
    BebliucGeorge almost 2 years

    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.