Will isset() trigger __get and why?
Asked Answered
T

5

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

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

Seems the answer is nope but why?

Transliterate answered 21/2, 2010 at 18:48 Comment(0)
P
19

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.

Persuasive answered 21/2, 2010 at 18:50 Comment(0)
P
2

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

Playoff answered 21/2, 2010 at 18:53 Comment(0)
T
1

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 :

Turf answered 21/2, 2010 at 18:51 Comment(2)
Seems I didn't define __isset in my example?Transliterate
Seems you didn't, indeed -- but, if you had defined it, it should have been called ;; and defining it or not doesn't change anything about __get not being called when you're testing if a property is set.Turf
S
0

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.

Spodumene answered 21/2, 2010 at 18:50 Comment(0)
H
0
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")
Heigho answered 23/2, 2013 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.