adis
adis

Reputation: 5951

Why isset() always returns FALSE on custom Object

I cannot understand this behavior: My isset() check is always returning false on a property that has a value for sure!

<?php

  class User {
    protected $userId; // always filled
    protected $userName; // always filled

    /**
     * Magic method for the getters.
     * 
     * @param type $property
     * @return \self|property
     */
    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        } else {
            throw new Exception('property '.$property.' does not exist in '.__CLASS__.' class');
        }
    }

  }

?>

When I check this variable from another class with the following:

isset($loggedUser->userName); // loggedUser is my instantiation of the User.php

It returns FALSE?? But when I overload the __isset() function in my User.php I get TRUE back as I expected:

public function __isset($name)
{
    return isset($this->$name);
}

Just to be clear:

echo $loggedUser->name;   // result "Adis"
isset($loggedUser->name); // results in FALSE, but why?

Thanks for your help!

Upvotes: 3

Views: 4211

Answers (4)

Flame
Flame

Reputation: 363

$userName is protected, which means you can't access it outside the class, in this example from your $loggedUser init. You need one of the following:
1) make it public
2) write a custom method
3) make a magic(__isset) function

EDIT: When using isset() on inaccessible object properties, the __isset() overloading method will be called, if declared.isset() php docs

I hope this explains it.

Upvotes: 5

Marc B
Marc B

Reputation: 360762

protected attributes are only visible from within the object's methods. They are hidden from view from outside access.


class prot_text {
    protected $cannot_see_me;
    function see_me() {
       echo $this->cannot_see_me;
    }
}

$x = new prot_text();
echo $x->cannot_see_me; // does not work - accessing from "outside"
$x->see_me(); // works, accessing the attribute from "inside".

Upvotes: 6

Jeff Davis
Jeff Davis

Reputation: 4797

This is because the property is protected. A protected property cannot be accessed outside of the object (or child objects). The overloaded function is defined within the class, so that works fine.

This a feature of OOP: (http://php.net/manual/en/language.oop5.visibility.php) If you want to make it accessible everywhere, define the property as public, otherwise wrap that particular function in a public function.

Upvotes: 1

Waxen
Waxen

Reputation: 1782

$userName is protected, so it's only accessible from inside the class it's defined in, or any classes that extend it.

Upvotes: 1

Related Questions