When do/should I use __construct(), __get(), __set(), and __call() in PHP?

后端 未结 10 712
再見小時候
再見小時候 2020-12-05 08:16

A similar question discusses __construct, but I left it in my title for people searching who find this one.

Apparently, __get and __set take a parameter that is the

10条回答
  •  暖寄归人
    2020-12-05 09:08

    PHP allows us to create class variables dynamically which can cause problems. You can use __set and __get methods to restrict this behavior..see the example below...

    class Person { 
          public $name;
          public function printProperties(){
           print_r(get_object_vars($this));
          }
    }
    
    $person = new Person();
    $person->name = 'Jay'; //This is valid
    $person->printProperties();
    $person->age = '26';  //This shouldn't work...but it does 
    $person->printProperties();
    

    to prevent above you can do this..

    public function __set($name, $value){
        $classVar = get_object_vars($this);
        if(in_array($name, $classVar)){
        $this->$name = $value;
        }
    }
    

    Hope this helps...

提交回复
热议问题