Dynamically call a static variable (array)

Here is my question for today. I create (for fun) a simple template engine. The basic idea is that I have a tag like this {blog: content}, and I break it down in method and action. The problem is that when I want to dynamically call a static variable, 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 get.

+3
source share
5 answers

How 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 display a "bubble"

+12
source

.

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

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

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

...

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

, PHP 5.3. Ahh, " " PHP 5.3

+5

, , :

echo eval( $class . "::" . $template[$action] );
0

, eval(). $class::$template  ( PHP), $template, ($class::$$template), PHP ( - PHP, IIRC).

I would recommend checking variables for valid names up to usng eval()though (the regular expression is copied from the PHP manual ):

if (!preg_match('[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*', $class)) {
    throw new Exception('Invalid class name (' . $class . ')');
}
0
source

Like everything in PHP, there are many ways to trick the same cat. I believe that the most efficient way to accomplish what you want is:

call_user_func(array($blog,$template));

See: http://www.php.net/manual/en/function.call-user-func.php

0
source

Source: https://habr.com/ru/post/1714053/


All Articles