Accessing a protected member variable outside a class

user275074 picture user275074 · Aug 13, 2010 · Viewed 41.3k times · Source

I'm querying for the ID of a field by accessing a class function which someone has already put in place. The result is a object returned with protected member variables. I'm struggling to see how I can access the member variable values outside the class.

Answer

Pawka picture Pawka · Aug 13, 2010

Accessing protected or private variables from public is incorrect (thats why they are protected or private). So better is to extend class and access required property or make getter method to get it publicaly. But if you still want to get properties without extending and if you are using PHP 5, you can acces with Reflection classes. Actually try ReflectionProperty class.

class Foo { protected $bar; }
$foo = new Foo();

$rp = new ReflectionProperty('Foo', 'bar');
$rp->setAccessible(true);
echo $rp->getValue($foo);