Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the magic function for empty() in PHP?

It should not be __isset,because isset() is not the same thing as empty()

like image 565
user198729 Avatar asked Mar 12 '10 08:03

user198729


2 Answers

As it says on this page:

__isset() is triggered by calling isset() or empty() on inaccessible properties.

There is no dedicated magic-method for empty()

If __isset() returns true, empty() will then invoke __get() to check the value of the property.

like image 117
Inspire Avatar answered Oct 09 '22 23:10

Inspire


As an addition to Inspire's answer:

class Foo {
  public function __isset($name) {
    echo "public function __isset($name)\n";
    return 'bar'===$name;
  }
  public function __get($name) {
    echo "public function __get($name)\n";
    return 'bar'===$name ? 0 : NULL;
  }
}

$foo = new Foo;
echo empty($foo->foo) ? ' empty' : ' not empty', "\n";
echo empty($foo->bar) ? ' empty' : ' not empty', "\n";

the output is

public function __isset(foo)
 empty
public function __isset(bar)
public function __get(bar)
 empty

meaning for the first property (foo) empty() only invoked __isset() which returned false -> empty($foo->foo)===true
For the second property (bar) __isset() was invoked and it returned true. Then the property is fetched via __get() and interpreted as a boolean value (see http://docs.php.net/language.types.type-juggling). And since (bool)0 is false, empty() also returns true for empty($foo->bar)

like image 22
VolkerK Avatar answered Oct 09 '22 21:10

VolkerK