What is the magic function for empty () in PHP?

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

+4
source share
4 answers

As the page says:

__ isset () is triggered by calling isset () or empty () on an inaccessible property.

There is no special magic method for empty ()

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

+13
source

In 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"; 

conclusion

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

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

+3
source

I think that in general you will find that the following PHP equivalent:

 isset($variable[0]) 

If, for example, the variable is a string, this would detect that the string is empty. It will work similarly for most primitive types (if not all).

0
source

property_exists() works if you just check if a class variable exists?

0
source

Source: https://habr.com/ru/post/1303907/


All Articles