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!
$userNameis protected, which means you can’t access it outside the class, in this example from your$loggedUserinit.You need one of the following:
1) make it
public2) 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.