Example class:
class Example{
public static $ONE = [1,'one'];
public static $TWO = [2,'two'];
public static $THREE = [3,'three'];
public static function test(){
// manually created array
$arr = [
self::$ONE,
self::$TWO,
self::$THREE
];
}
}
Is there a way in PHP to get an array of class static member variables without creating it manually like in the example?
A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the 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.
We can access the static member function using the class name or class' objects. If the static member function accesses any non-static data member or non-static member function, it throws an error. Here, the class_name is the name of the class. function_name: The function name is the name of the static member function.
Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.
Yes there is:
Using Reflection, and the getStaticProperties() method
class Example{
public static $ONE = [1,'one'];
public static $TWO = [2,'two'];
public static $THREE = [3,'three'];
public static function test(){
$reflection = new ReflectionClass(get_class());
return $reflection->getStaticProperties();
}
}
var_dump(Example::test());
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With