4
$user = new User(1);

var_dump($user->ID);
if (empty($user->ID))
    echo "empty";

// output string(2) "77" empty

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

The 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 not empty var empty($user->ID) it will return false, but when using isset($user->ID) on a declared var which is empty (e.g. $user->ID = '') it will also return false, because isset() will call __isset() inside the class, right?

Is there a way to fix this behaviour? PHP notes, that I should copy the overloaded property into a local variable, which seems too much paperwork for me ;)

Chris
  • 4,255
  • 7
  • 42
  • 83

3 Answers3

9

empty() doesn't call __get(). You need to implement __isset().

Eran
  • 387,369
  • 54
  • 702
  • 768
Rob
  • 12,659
  • 4
  • 39
  • 56
2

Quoting from the manual:

Note:

It is not possible to use overloaded properties in other language constructs than isset(). This means if empty() is called on an overloaded property, the overloaded method is not called.

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
2

According to the docs, you should overload __isset() for empty to work

Steve Lazaridis
  • 2,210
  • 1
  • 15
  • 15