Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get all static properties of a Class in php

Tags:

php

class

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?

like image 798
Ray Avatar asked Mar 14 '12 14:03

Ray


People also ask

How can I get static properties in PHP?

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 .

How do you find the properties of a static method?

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.

How use $this in static method in PHP?

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.

Can we inherit static method in PHP?

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".


2 Answers

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
}
like image 148
Matt Gibson Avatar answered Oct 11 '22 11:10

Matt Gibson


Use the Reflection

<?php
require_once "Foo.php";
$reflection = new ReflectionClass("Foo"); 
$staticProperties = $reflection->getStaticProperties();
print_r($staticProperties)
  • http://php.net/manual/en/reflectionclass.getstaticproperties.php
  • http://ca2.php.net/manual/en/reflectionclass.getstaticpropertyvalue.php
like image 34
roychri Avatar answered Oct 11 '22 13:10

roychri