I have a static class Foo (this isn't a real class, so static fields are just for 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 the public static properties and their current values.
Is there a quick/easy way anyone can suggest to do this without instantiating a Foo?
Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ). print $foo::$my_static .
In order to define methods and properties as static, we use the reserved keyword static. In the following example, the class Utilis has a static public property with the name of $numCars and so the variable name is preceded by both the static and the public keywords.
In the static method,properties are for the class, not the object. This is why access to static methods or features is possible without creating an object. $this refers to an object made of a class, but $self only refers to the same class.
PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance. More precisely, late static bindings work by storing the class named in the last "non-forwarding call".
Use a ReflectionClass
instance like this to get an array of the property names and values:
$class = new ReflectionClass('Foo');
$staticProperties = $class->getStaticProperties();
foreach ($staticProperties as $propertyName => $value) {
// Your code here
}
Use the Reflection
<?php
require_once "Foo.php";
$reflection = new ReflectionClass("Foo");
$staticProperties = $reflection->getStaticProperties();
print_r($staticProperties)
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