phpstrict

Enforcing strict comparison for bool return type functions in PHP


Given: if ($var) is a loose comparison as in if ($var == true)

strict comparison will be if ($var === true)

should also bool return type function be explicitly enforced?

es:

if (isset($var) === true) or if (isset($var) === false)

if ($this->isEnabled($var) === true) or if ($this->isEnabled($var) === false)

instead of:

if (isset($var)) or if (!isset($var))

if ($this->isEnabled($var)) or if (!$this->isEnabled($var))

considering it as good practice to use strict comparison and improve readability?

PS: the above functions are just for example


Solution

  • PHP is a loosely typed language, thus you need strict comparisons, right?

    Well, no. Not at least in every single place where boolean logic is involved.

    The only case where you ever need to make a strict comparison against a boolean value is when the function can return two different falsy (or truthy) values that you want to distinguish. A typical case is mysqli_fetch_assoc():

    Return Values

    Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, null if there are no more rows in the result set, or false on failure.

    When using it, you absolutely need to determine whether you don't have any rows or the function call failed*.

    (*) Let's pretend that mysqli is not configured to throw exceptions on errors.

    var_dump((bool)null, (bool)false);
    
    bool(false)
    bool(false)
    

    You say that isset() is just an example, but it's an example where you do not need strict comparison, because it cannot return a non-boolean:

    Return Values

    Returns true if var exists and has any value other than null. false otherwise.

    You need strict comparisons when automatic type casting is not desired. Look at this:

    $pin = '000123';
    if ($pin == '123' ) {
        echo "PIN is correct\n";
    }
    
    PIN is correct
    

    Is it good practice to do it everywhere, needed or not?

    I've seen developers arguing that this improves readability:

    if ($order->hasInvoice() === true) {
    }
    

    That's subjective and I won't pontificate on it, but this style also leads to:

    if ($order->hasInvoice() === false) {
    }
    

    Just decide whether you find that more readable than:

    if (!$order->hasInvoice()) {
    }