Reputation: 8893
How do I delcare a variable in an if statment that only goes in the if
block if the variable is not a nullish value?
Also, what is the scope of the $var
in code like:
if(($var = funky()) != null) {}
Can I reference $var
outside the if
block?
Upvotes: 2
Views: 438
Reputation: 41810
An assignment expression in PHP returns the assigned value. From the documentation:
The value of an assignment expression is the value assigned.
So if whatever funky()
returns evaluates to something loosely equal to null
, $var = funky()
will evaluate to false, so the if
block will not be executed.
Doing the assignment in the if
condition does not affect the scope of the assigned variable, though. $var
will be available in the current scope (inside and outside the if block) after the assignment statement.
For example:
function funky() {
return false;
}
if(($var = funky()) != null) {
echo 'something';
}
var_dump($var);
Here, you'll just see boolean false
The only way I can think of to ensure that a variable is only available inside an if
block is to assign it there and unset it before the end of the block.
if (funky() != null) { // evaluate funky() without assigning
$var = funky(); // call funky() again to assign
// do stuff
unset($var);
}
But I can't really think of any good reason to do this.
Upvotes: 2