Casting object to array - any magic method being called?

前端 未结 6 1830
梦谈多话
梦谈多话 2020-12-10 00:44

I have an object of class Foo:

class Foo extends Bar {
    protected $a;
    protected $b;
}

$obj = new Foo();

What I want (and have) to d

6条回答
  •  青春惊慌失措
    2020-12-10 01:14

    One way to do this, without changing the original class definition is to use reflection. This allows to you examine the class's properties at runtime.

    Taken from the manual: http://www.php.net/manual/en/reflectionclass.getproperties.php

    getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
    
    foreach ($props as $prop) {
        print $prop->getName() . "\n";
    }
    
    var_dump($props);
    
    ?>
    
    The above example will output something similar to:
    foo
    bar
    array(2) {
      [0]=>
      object(ReflectionProperty)#3 (2) {
        ["name"]=>
        string(3) "foo"
        ["class"]=>
        string(3) "Foo"
      }
      [1]=>
      object(ReflectionProperty)#4 (2) {
        ["name"]=>
        string(3) "bar"
        ["class"]=>
        string(3) "Foo"
      }
    }
    

提交回复
热议问题