oop - Difference between php __set(), __get and simple seting, getting function -


i'm not sure value in having __get , __set methods in php.

here code set value in array.

class myclass { public $sotre = array();  public function __set($arraykey,$value){     echo 'setting '.$arraykey.' '.$value;     $this->store[$arraykey] = $value; }  }  $obj = new myclass; $obj->a = 'arfan'; 

here code.

 class myclass { public $sotre = array();  public function setvalue($arraykey,$value){     echo 'setting '.$arraykey.' '.$value;     $this->store[$arraykey] = $value; }  }  $obj = new myclass; $obj->setvalue('a','arfan'); 

both functions same thing.

code using __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 see these both function same work.

i'm confused why php developers use magic methods __get/__set when can implemented yourself?

i'm sure there use them must missing something.

it's not when invoked.

__set() run when writing data inaccessible properties.  __get() utilized reading data inaccessible properties. 

so if want

echo $object->propertdoesnexists; //it call 

but this

$object->propertdoesnexists = 1; //it call set 

the example of using , set methods here

using magicmethods makes code easier read , shorter.

there more interesting magicmethods

i've noticed use $store array public! there no sense in it. if marks public accessible without using methods. not point of it. when use methods or magic methods get/set variable because methods gives better control when want assign or variable, can validation, check against errors etc. making variables public known bad convention. public members can accessed outside class in every place of project, if error occurs there lot of code check, when goes wrong private member accessed method there 2 methods check(get/set).


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -