Empty () returns an invalid result

$user = new User(1); var_dump($user->ID); if (empty($user->ID)) echo "empty"; // output string(2) "77" empty 

So, why empty () returns true even when $user var is not empty?

Relevant parts of my User class:

 class User { protected $data = null; public function __construct($userID) { // sql select $this->data = $sqlResult; } // ... public function __get($name) { if (isset($this->data[$name])) return $this->data[$name]; else return null; } } 

UPDATE:

So, I updated my User class and added the __isset () method

 public function __isset($name) { if (isset($this->data[$name]) && !empty($this->data[$name])) return true; else return false; } 

This leads me to another problem: When calling empty() on my non- empty($user->ID) var empty($user->ID) it will return false, but when using isset($user->ID) in the declared var, which is empty (for example, $user->ID = '' ), it will also return false, because isset() will call __isset() inside the class, right?

Is there any way to fix this behavior? PHP notes that I have to copy the overloaded property into a local variable, which means too many documents for me;)

+4
source share
3 answers

empty() does not call __get() . You need to implement __isset() .

+8
source

Quote from manual :

Note :

It is not possible to use overloaded properties in constructs of languages ​​other than isset (). This means that if empty () is called with an overloaded property, the overloaded method is not called.

+2
source

According to the docs you have to overload __ isset () for empty to work

+2
source

All Articles