7

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

user198729
  • 61,774
  • 108
  • 250
  • 348

4 Answers4

17

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.

Inspire
  • 2,052
  • 15
  • 14
  • So the result is always the same or `isset()` or `empty()` ? – user198729 Mar 12 '10 at 08:39
  • Yes, if your __isset method returns true, both empty() and isset() will return true. You probably should implement a "non-magic" method to do the check for empty(), and keep __isset only for isset() – Inspire Mar 12 '10 at 08:44
  • Hmm as a matter of fact, it seems empty() returns true if the __isset method returns false but isset() returns false in this case. If __isset returns true, they both return true (tested on PHP 5.3.0) – Inspire Mar 12 '10 at 08:48
  • So I guess it first calls `__isset`,then `__get`? – user198729 Mar 12 '10 at 08:51
  • That seems to be right and makes sense (I didn't write a __get method in my test code which must have been why empty() was always returning true). – Inspire Mar 12 '10 at 09:02
5

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)

VolkerK
  • 95,432
  • 20
  • 163
  • 226
0

I think in general you'll find that the following is the PHP equivalent:

isset($variable[0])

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

Fenton
  • 241,084
  • 71
  • 387
  • 401
0

doesn't property_exists() work for you if you're just testing if a class variable exists?

Smamatti
  • 3,901
  • 3
  • 32
  • 43
bcosca
  • 17,371
  • 5
  • 40
  • 51