headphono.us

Avatar

Pras Sarkar blogs about web technology, music, social networks, digital identities and other random things.

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.

Tags

No Comments, Comment or Ping

Reply to “A neat trick to expose PHP objects’ private properties”

My Lifestream

My shenanigans around the web