Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of static variables in a class?

With a class like

class MyClass {
    static var1 = "a";
    static var2 = "b";
}

... I'd like to retrieve the static members and their values at runtime; something like

Array(
    "var1" => "a",
    "var2" => "b"
)

Is there any way to do this in PHP?

like image 459
Phillip Avatar asked Jan 06 '12 20:01

Phillip


People also ask

How do you view static variables in a class?

A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.

How do you access static variables?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

How many copy of a static variable is available for the entire class?

Static variables and methods belong to a class and are called with the Class Name rather than using object variables, like ClassName. methodName(); There is only one copy of a static variable or method for the whole class.

How do you access static variables outside the class?

From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.


2 Answers

You can use ReflectionClass::getStaticProperties() to do this:

$class = new ReflectionClass('MyClass');
$arr = $class->getStaticProperties();
Array
(
    [var1] => a
    [var2] => b
)
like image 199
Tim Cooper Avatar answered Oct 09 '22 21:10

Tim Cooper


http://www.php.net/manual/en/reflectionclass.getstaticproperties.php - try this

getting information about classes and class properties such as all static methods is called "reflection".

like image 29
tehdoommarine Avatar answered Oct 09 '22 21:10

tehdoommarine