I'm not sure what the value is in having __get and __set methods in PHP.
Here is the code which set the value in array.
class myclass {
public $sotre = array();
public function __set($arraykey,$value){
echo 'Setting '.$arraykey.' to '.$value;
$this->store[$arraykey] = $value;
}
}
$obj = new myclass;
$obj->a = 'arfan';
Here is another code.
class myclass {
public $sotre = array();
public function setvalue($arraykey,$value){
echo 'Setting '.$arraykey.' to '.$value;
$this->store[$arraykey] = $value;
}
}
$obj = new myclass;
$obj->setvalue('a','arfan');
Both functions do the same thing.
Code using the __get/__set magic methods:
class myclass {
public $store =
array(
'a'=>'arfan',
'b'=>'azeem',
'c'=>'hader'
);
public function __get($arraykey){
echo 'Getting array key '.$arraykey.'<br />';
if(array_key_exists($arraykey,$this->store)){
return $this->store[$arraykey];
}
}
public function getvalue($arraykey){
echo 'Getting array key '.$arraykey.'<br />';
if(array_key_exists($arraykey,$this->store)){
return $this->store[$arraykey];
}
}
}
$obj = new myclass;
echo $obj->a;
$obj = new myclass;
echo $obj->getvalue('a');
As you see these both function do same work.
I'm confused as to why PHP developers would use the magic methods __get/__set when they can be implemented yourself?
I'm sure there is some use for them but I must be missing something.
$obj->ais more readable than$obj->getvalue('a')...