The easiest way to get all the static properties of a class in php

I have a static class Foo (this is not a real class, so static fields are just an example)

class Foo{ public static $name = "foo"; public static $age = "18"; public static $city = "Boston"; } 

In my code, I want to build an array of all public static properties and their current values.

Is there a quick / easy way anyone can suggest to do this without instantiating Foo?

+4
source share
3 answers

Use an instance of ReflectionClass like this to get an array of property names and values:

 $class = new ReflectionClass('Foo'); $staticProperties = $class->getStaticProperties(); foreach ($staticProperties as $propertyName => $value) { // Your code here } 
+8
source

Use Reflection

 <?php require_once "Foo.php"; $reflection = new ReflectionClass("Foo"); $staticProperties = $reflection->getStaticProperties(); print_r($staticProperties) 
+5
source

get_class_vars () is your friend!

Make it a fantasy:

 echo '<pre>';

 echo var_dump (get_class_vars (--- your class name ---));

 echo '</pre>';

0
source

Source: https://habr.com/ru/post/1401395/


All Articles