Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to get dynamic instance variables via PHP's reflection

Tags:

php

reflection

I failed to get dynamic instance variables via PHP's reflection

Sample code:

<?php

class Foo
{
    public function bar()
    {         
        $reflect = new ReflectionClass($this);
        $props   = $reflect->getProperties();
        var_export($props);
        die;
    }
}

$foo = new Foo();
$foo->a = "a";
$foo->b = "b";

$foo->bar(); // Failed to print out variable a and b

Any idea?

like image 466
Howard Avatar asked Dec 12 '22 16:12

Howard


1 Answers

ReflectionClass::getProperties() gets only properties explicitly defined by a class. To reflect all properties you set on an object, use ReflectionObject which inherits from ReflectionClass and works on runtime instances:

$reflect = new ReflectionObject($this);

Or as Tim Cooper says, forget reflection and just use get_object_vars() instead.

like image 152
BoltClock Avatar answered Dec 15 '22 06:12

BoltClock