Error creating variable inside IF

2

I was creating a script that always worked for me, however, I made a small change that almost exploded my mind because I did not understand what happened and I did not find anything on the subject. It is as follows:

This code works perfectly:

$true1 = true;

if(!$true1 || !($id = true)){
    exit;
}

var_dump($id);

Returned value bool (true)

However, when I change || by && it generates an undefined variable error:

  

PHP Notice: Undefined variable: id in /home/vHrTJp/prog.php on line   11

$true1 = true;

if(!$true1 && !($id = true)){
    exit;
}

var_dump($id);

Returning the value NULL

This also works:

if(!($id = true)){
    exit;
}

var_dump($id); // bool(true)

How is this possible?

None of the above conditions should return an error .. right? Or not?

    
asked by anonymous 15.09.2018 / 22:55

1 answer

3

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.

    

15.09.2018 / 23:16