-2

I know about questions like this one. There are lots of them with great answers.

I know this was "fixed" in PHP 5.5.x, but I'm unfortunately I'm using 5.3.x.

$iHatePHP = $node->get($key);
if (isset($node->get($key)) ...

The error I get:

Fatal error: Can't use method return value in write context in ...

I know the "fix" is to put the result of get() into a variable and call isset() on that. However, in order to save writing that thousands of times in my code, is it equivalent or am I missing some cases?

$iHatePHP = $node->get($key);
if (!($node->get($key)) ...

Edit: I control get(). So I can make it return anything I like, such as NULL, FALSE or ""

Community
  • 1
  • 1
Pepster K.
  • 339
  • 2
  • 5
  • 17

1 Answers1

2

The isset() pseudo-function checks not for a variable that would cast to false, but for one which is null. Additionally, it checks for a variable or array key's existence; a non-existent variable would be null anyway, but would also issue a Notice, in case you had mistyped the name or similar.

When you are testing the result of a function or method call, you know that there is some return value (a function with no return statement, or a plain return; with no value, is returning null), so the extra case of "no such variable" is impossible. The easiest way to test the value is therefore is_null:

if ( is_null($node->get($key)) ) ...

If $node->get($key) returns false, 0, or '', the ! version would enter the if statement due to the rules on converting other types to boolean.

The similar empty() construct does evaluate as though you had applied a ! operator, but preserves the special behaviour for non-existent variables - empty($foo) is effectively the same as ! isset($foo) || ! (bool)$foo.

IMSoP
  • 89,526
  • 13
  • 117
  • 169