PHP: accessing protected and private members with __get

As their name says, protected and private members in PHP are not directly accessible from outside a given class. When you define such members, usually you should set a getter to retrieve their values or just to access them even outside a class definition. The problem with getters is that you should define a getter for each member you want to access. Fortunately, PHP provides the magic method called __get() for that purpose.

Inside a given class, you define this magic method by strictly following this syntax:

 public function __get($prop)
{

        return $this->$prop;

}

And you're done. Now, let's build a test. Given the following class:

class A
{

    public $a = 'Public';
    protected $_b = 'Protected';
    private $_c = 'Private';
}

Accessing a public method is really easy:

$A = new A();
echo $A->a;

This will simply output 'Public', as expected. But if you try to access a protected or private member without a getter:

try {
	echo $A->_b;
	echo $A->_c;

} catch(Exception $e) {

	echo $e->getMessage();

}

you get a fatal error:

Fatal error: Cannot access protected property A::$_b

So you have to rewrite your class as follows:

class A
{

    public $a = 'Public';
    protected $_b = 'Protected';
    private $_c = 'Private';

    public function __get($prop)
    {

        return $this->$prop;

    }

}

And if you try to test this out:

$A = new A();

echo $A->a . '<br/>';

try {
	echo 'Using __get() ... ' . '<br />';
	echo $A->_b . '<br/>';
	echo $A->_c;

} catch(Exception $e) {

	echo $e->getMessage();

}

you get your desired result.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.