Unable to get static variable from class $

I have a question regarding the initialization of the dynamic class, let me explain what I mean:

$class = 'User';
$user = new $class();

//...is the same as doing
$user = new User();

So ... this is not a problem, but I am having problems with the same call when calling a static variable from a class, for example:

$class = 'User';
print $class::$name;

It produces the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in

The course that I tested while completing did not pass print User::$name;, and it works. So the class is working.

Why is this so around?

Next question:
Is there any good reason not to use this “dynamic” way to create classes?

+5
source share
3 answers

PHP 5.3 , (, , - ), getter call_user_func():

class A {
    public static $var = "Hello";
    public static function getVar() {
        return self::$var;
    }
}
$className = "A";
echo call_user_func(array($className, 'getVar'));
+1

PHP 5.4.3:

<?php

class A {
    public static $var = "Hello";
}

print(A::$var);

$className = "A";
print($className::$var);

?>
+2

This is the answer to the question I asked in the comments:

You can use reflection for this. Create a ReflectionClass object specified by the class name, and then use the getStaticPropertyValue method to get the value of the static variable.

class Demo
{
    public static $foo = 42;
}

$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);
+2
source

All Articles