Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get static variable from $class

Tags:

scope

php

class

I have a question regarding "dynamic" class initialising, let me explain what I mean:

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

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

So... that's not the problem, but I am having some trouble doing the same while calling a static variable from a class, for example:

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

Which gives out the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in

Off course I have tested doing print User::$name; and that works. So class works.

Why is this and is there a way around it?

Follow up question:
Also is there any valid reasons to not use this "dynamic" way in creating classes?

like image 599
jamietelin Avatar asked Aug 23 '12 08:08

jamietelin


2 Answers

This code works good on PHP 5.4.3:

<?php

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

print(A::$var);

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

?>
like image 174
Dmytro Zarezenko Avatar answered Sep 22 '22 14:09

Dmytro Zarezenko


This is the answer from the question I linked in the comments:

You can use reflection to do this. Create a ReflectionClass object given the classname, and then use the getStaticPropertyValue method to get the static variable value.

class Demo
{
    public static $foo = 42;
}

$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);
like image 24
Thomas Clayson Avatar answered Sep 22 '22 14:09

Thomas Clayson