Accessing a protected member variable outside a class
Here is the correct answer:
We can use bind() or bindTo methods of Closure class to access private/protected data of some class, for example:
class MyClass {
protected $variable = 'I am protected variable!';
}
$closure = function() {
return $this->variable;
};
$result = Closure::bind($closure, new MyClass(), 'MyClass');
echo $result(); // I am protected variable!
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);