Will isset() trigger __get and why?

女生的网名这么多〃 提交于 2019-11-29 18:50:13

问题


class a {
   function __get($property){...}
}

$obj = new a();
var_dump(isset($obj->newproperty));

Seems the answer is nope but why?


回答1:


Because it checks __isset rather than retrieving it using __get.

It is a much better option to call __isset, as there is no standard on what is empty. Maybe in the context of the class null is an acceptable value. You could also have a class that if the member didn't exist, it returned a new empty object, which would break isset($myObj->item) as in that case it would always return true.




回答2:


It just isn't; you can use __isset instead. This is laid out here.




回答3:


No, __get should not be triggered when you're trying to determine whether a property is set : testing if a property is set is not the same thing as trying to get its value.

Using isset triggers the __isset magic method.

See :

  • isset
  • and Overloading



回答4:


The magic function __get is only called when you try to access a property that doesn't exist. Checking whether a property exists is not the same as retrieving it.




回答5:


Class A{
   public function __get($key){
      ...
   }
   public function __set($key,$name){
      ...
   }
   public function __unset($key){
      ...
   }
   public function __isset($key){
      ...
   }
}
$obj = new A();
$get = $obj->newproperty;//$obj->__get("newproperty")
$obj->newproperty = "X";//$obj->__set("newproperty","X")
$bool = isset($obj->newproperty);//$obj->__isset("newproperty")
unset($obj->newproperty);//$obj->__unset("newproperty")


来源:https://stackoverflow.com/questions/2306979/will-isset-trigger-get-and-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!