Mar 9, 2010
A neat trick to expose PHP objects’ private properties
If you’ve ever needed to write up a PHPUnit test that requires you to check the value of a private property, you can try accessing the private member variables like so:
<?php class foo { private $bar = 42; } $obj = new foo; $propname="\0foo\0bar"; $a = (array) $obj; echo $a[$propname]; ?>
Or PHP 5.3+ using Reflections:
<?php static function expose($obj, $prop) { $reflection = new ReflectionClass($obj); $prop = $reflection->getProperty($prop); return $prop->getValue($obj); } ?>
Great tip from Derick Rethans.
PrasSarkar.com
No Comments, Comment or Ping
Reply to “A neat trick to expose PHP objects’ private properties”