Reputation: 1056
I'm trying to get all properties of a Class using Reflection, but some properties are still messing.
Here a small exemple of what happens in my code
Class Test {
public $a = 'a';
protected $b = 'b';
private $c = 'c';
}
$test = new Test();
$test->foo = "bar";
So at this point my $test object has 4 properties (a, b, c and foo).
The foo property is considered as a public property because I can do
echo $test->foo; // Gives : bar
On the contrary b or c are considered as private properties
echo $test->b; // Gives : Cannot access protected property Test::$b
echo $test->c; // Gives : Cannot access private property Test::$c
I tried two solutions to get all properties (a, b, c and foo) of my $test object
The first
var_dump(get_object_vars($test));
Which gives
array (size=2)
'a' => string 'a' (length=1)
'foo' => string 'bar' (length=3)
And the second solution
$reflection = new ReflectionClass($test);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED);
foreach($properties as $property) {
echo $property->__toString()."<br>";
}
Which gives
Property [ public $a ]
Property [ protected $b ]
Property [ private $c ]
In the first case, private properties are missing, and in the second case "after instantiation" properties are missing.
No idea of what can I do to get all properties ?
(preferably with Reflection, because I also want to know if a property is public, private...)
Upvotes: 2
Views: 544
Reputation: 157990
Use ReflectionObject
instead of ReflectionClass
if you also need to list dynamically created object properties:
$test = new Test();
$test->foo = "bar";
$class = new ReflectionObject($test);
foreach($class->getProperties() as $p) {
$p->setAccessible(true);
echo $p->getName() . ' => ' . $p->getValue($test) . PHP_EOL;
}
Note that I've used ReflectionProperty::setAccessible(true)
in order to access the value of protected
or private
properties.
Output:
a => a
b => b
c => c
foo => bar
Upvotes: 3