Search code examples
phpisset

isset() creating an Object property


today, I found an problem when I tested my app and I don't know, how to explain this:

I have got simple condition:

if(isset($entity->filter)) {
    $var = "text";    
}

Server return

Object { id: 0, name: "a", link: "a" }

OK (expected object is returned)

But when I changed my condition to this:

if(isset($entity->filter["where"])) {
    $var = "text";    
}

Server return

Object { id: 0, name: "a", link: "a", filter: null }

ERROR (object have set "filter" property)

Can you explain to me, why the isset() function in second condition will set the "filter" property to my object?

// EDIT

I create a test PHP code, which can reproduce the error above:

<?php

class testObj {

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

    public function &__get($name) {
        return $this->$name;
    }

}

$obj = new testObj();

$obj->p1 = "test";
$obj->p2 = 10;
$obj->p3 = true;

var_dump($obj);

if(isset($obj->p4["arr"])) {
    // do something
}

var_dump($obj);

Output

object(testObj)#1 (3) { ["p1"]=> string(4) "test" ["p2"]=> int(10) ["p3"]=> bool(true) } object(testObj)#1 (4) { ["p1"]=> string(4) "test" ["p2"]=> int(10) ["p3"]=> bool(true) ["p4"]=> NULL }


Solution

  • In the first condition isset() access $entity an checks if the property exists. In the Seccond condition you explicit access the property $entity->filter. When you access a property what das not exists the property will be generated and initialize with null. Then you can use it or assign a value to it. Because isset() access the property to checks if it is an array what have the key "where", it generate an property with null. This is called Overloading to generate dynamically properties: http://php.net/manual/en/language.oop5.overloading.php