Should the overloaded __get manage all member variables?
I am creating a __get () function for a class to control access to my private member variables. Do I need to create a function to handle all possible member values, or am I unable to write one for public users? Also, I am assuming that classes inheriting this class will use my __get () function to access private members.
class ClassA{
private $collection = array();
public $value;
function __get($item){
return $collection[$item];
}
a source to share
No, you don't.
class A {
public $foo = 'bar';
private $private = array();
public function __get($key) {
echo 'Called __get() at line #' ,__LINE__, ' with key {', $key ,'}',"\n";
return $this->private[$key];
}
public function __set($key, $val) {
$this->private[$key] = $val;
}
}
$a = new A();
var_dump($a->foo);
$a->bar = 'baz';
var_dump($a->bar);
And yes it will:
class B extends A { private $private = array(); }
$b = new B();
var_dump($b->bar);
a source to share
Well, your code won't work with private parts not set in your array. But then again, you can use this as a way to deal with what goes into and out of your array as such;
function __get($item){
if ( isset ( $collection[$item] ) )
return $collection[$item];
else {
try {
return $this->$item ; // Dynamically try public values
} catch (Exception $e) {
$collection[$item] = 0 ; // Make it exist
}
}
}
Classes that inherit from your calls will use this __get (), but can be overridden, so use the parent :: __ construct () function for explanation. Also note that they cannot be static. Further reading .
a source to share
PHP first looks for the property name in the class definition and tries to return its value. If there is no property - PHP tries to call __get ($ var) and here you can return whatever you want. This is a little confusing behavior for those who know Java-like getters / setters, where you have to define them for each member of the class you want to access.
When it's convenient to use Java-like getters / setters - you can write something like this:
public function __set($var, $value)
{
if (method_exists($this, $method = "_set_" . $var))
{
call_user_func(array($this, $method), $value);
}
}
public function __get($var)
{
if (method_exists($this, $method = "_get_" . $var))
{
return call_user_func(array($this, $method), $value);
}
}
and then use this code by defining custom getters / setters
protected function _get_myValue()
{
return $this->_myValue;
}
protected function _set_myValue($value)
{
$this->_myValue = $value;
}
and accessing specific methods like this:
$obj->myValue = 'Hello world!';
a source to share