0

I am developing a PHP application. Now, I am trying to loop through all the static/ const properties of a PHP class maybe through reflection.

I have a class like this

class MyClass
{
   const MY_CONST = "my_const";
   public static $MY_STATIC_PROP = "my_static_prop";
}

What I want to do is that I want to loop through all the properties of a class and check if the name of the property is equal to something.

if ($property_name == "something") {
    //do something
}

How can I do that in PHP?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

0

To get private and public properties you can use get_object_vars() and for const and static properties can use ReflectionClass() class object. Finally merge all the properties. Example:

class MyClass
{
    const MY_CONST = "my_const";
    public static $MY_STATIC_PROP = "my_static_prop";
    public $pub = 'Pub';
    public $pvt = 'Pvt';
}

$ref = new ReflectionClass('MyClass');

$allProperties = get_object_vars(new MyClass) + $ref->getConstants() + $ref->getStaticProperties();

foreach ($allProperties as $name => $vale) {
    if ($name === 'something') {
        // do stuff
    }
}
MH2K9
  • 11,951
  • 7
  • 32
  • 49