Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an array of class static member variables

Tags:

php

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?

like image 837
James May Avatar asked Dec 27 '15 13:12

James May


People also ask

How do you access static class members?

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.

How do you find the static class of a variable?

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 member functions?

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.

How do you declare a static array in C++?

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.


1 Answers

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

like image 150
Mark Baker Avatar answered Sep 18 '22 09:09

Mark Baker