Let's look at the code that matters:
!$true1 && !($id = true)
The first expression to evaluate is the negation of the $true1
variable. The result is false. As next comes a &&
operator which forces both operands to be true
so that the end result is true
. Well, he already knows that on the one hand it is false, so it is impossible for 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 $id
variable is never created, and when you print it it obviously gives error.
The failure of PHP is to let a variable be or not be created conditionally. It is a language error, but knowing this you have to follow this rule.
For completeness of explanation, the expression
$true1 || !($id = true)
would also give the same error. The first gives true
, and in case of ||
just one of them is true
, then he already knows that the whole will be true, so he does not have to evaluate the second part.
In the case of the example, it worked because the first part gives false, so it is necessary to evaluate the second part to be sure if it will be false or could be true.
This is called short circuit .
The last code obviously works because the expression is unique and will always be evaluated, so the variable is created.
However, avoid creating variables as an expression. Even assigning a value to a variable within an expression is not a big problem, although it is recommended to use carefully, create should even be forbidden by the language, but in PHP it is not. Just create variables like statement . But if you create it, then be careful to test before using the variable that may have been created or not.