About variables - A best practice question

Hello all,

I’ve just found out that, we can store other things then values on variables; OR, that “value”, actually, means more then I was expecting to mean.

On the following excerpt:


$fieldsAreFilled = (!empty($hostNameInput) && !empty($hostAddressInput));
$hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);

if ($fieldsAreFilled && !$hostInfoEqualsInput) {
    ...
}

We are storing a “condition” into a variable?
Is there a name for this kind of operation, so that we can learn more about it?

Thanks a lot,
Márcio

The if will be entered if $fieldsAreFilled is true AND !$hostInfoEqualsInput is true, that is: if $fieldsAreFilled is true AND $hostInfoEqualsInput is false!
So:
This condition must be true: (!empty($hostNameInput) && !empty($hostAddressInput))
This condition must be false: ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput)

@Kalon: yes… it was a missunderstanding of my part. :wink:

AHHHH!! It’s a convention. Ok. I thought you are telling that, for no matter what if statement, of no matter what circumstances, the first condition must be true.

I lost the context of my own answer! How worst can I get?! :S
Oh well… thanks a lot, your explanation clear it out. :slight_smile:

The ! means “not”.

eg.

$var = 5;

!empty($var) will evaluate to true

Why?

Yes. !FALSE == TRUE but… I’m
missing the connection dots here… :crazy:

You are not storing a condition, you are storing the result of that condition: the value TRUE or FALSE. So the variable still contains a value :slight_smile:

Ahh! Thanks Guido.

So, later, when we do:

if ($fieldsAreFilled && !$hostInfoEqualsInput) {
    ...
} 

What are we doing?

if (true && !true) 
{
//??
}

:nono:

Yes. Or


if (true && !false) {
//??
} 

It depends on the result of the conditions. To enter the if, the first condition must be TRUE, the second FALSE (because !FALSE == TRUE :slight_smile: ).

Well to take things one level of confusion deeper, the truthiness of each comparison is only calculated when the conditions before them are valid.

What does that mean? Delayed operations.

When a function such as foo() might throw a warning or an error, you can perform some kind of check before it, and the function will only be called when the check is valid.

With the following code, the foo() function will never be called. The first condition acts as a guard, so you can check if some condition is correctly met before running something.


$a = (false && foo());
$b = (true  || foo());

There’s more on this too at the logical operators documentation page.