Let’s look at the code that matters:
!$true1 && !($id = true)
The first expression to be evaluated is the negation of the variable $true1
. The result is false. As next comes an operator of &&
which requires both operands to be true
for the final result to be true
. Well, he already knows that on the one hand it is false, so it is impossible the whole expression to be true
. Why would he waste time trying to evaluate the second part of the expression (!($id = true)
) if it becomes irrelevant? It is not running and the variable $id
is never created, and when sent to print it obviously gives error.
The failure of PHP there is to let a variable be created conditionally or not. It’s a language mistake, but knowing that you have to follow this rule.
To complete of explanation the expression
$true1 || !($id = true)
I put in the Github for future reference.
would also give the same error. The first gives true
, and in the case of ||
just one of them being true
, then he already knows that the whole will be true, so there is no need to evaluate the second part.
In the case of the example it worked because the first part is false, then it is necessary to evaluate the second part to be sure whether it will be false or may be true.
That’s called short-circuit.
The last code obviously works because the expression is unique and will always be evaluated, so the variable is created.
Anyway avoid creating variables as expression. Until assigning a value to a variable within an expression is not a big problem, although it is recommended to use it carefully, creating should even be prohibited by the language, but in PHP is not. Just create variables like statement. But if creating, then take care to test before using the variable that may or may not have been created.
Interestingly it has language, like C#, that allows creating the variable conditionally, but since it was purposeful and not an accident, it only lets you use the variable within the condition being true.
I misread the comment, disguise
– Everton Neri
@Evertonneri didn’t even read it. =)
– Andrei Coelho