Jens A. Koch

The power of a short-circuit “or” – quite boring and often forgotten.


function AVeryExpensiveCallWithBooleanReturnValue()
{
    echo __METHOD__ . ' executed.';
    return (bool) rand(0,1);
}

$bool = true;

if($bool or AVeryExpensiveCallWithBooleanReturnValue())
{
    echo 'First condition "true". Second condition "not evaluated" (short-circuited).';
}

Have you seen return (bool) rand(0,1);? Stupid? Yes? Really?
It’s a very helpful snippet during testing the logical context of a boolean return function.

I wish for an automated tool, doing this kind of stuff to the code. Sadly, there isn’t a single one in the PHP world. Maybe, Scrutinizer-CI at some, not so far, future day. If one has basic flow-path analysis, it’s not that far away, to do enhanced logical analysis (including boolean return value modification), too.

http://www.php.net/manual/en/language.operators.logical.php

Comments Off on The power of a short-circuit “or” – quite boring and often forgotten.

Comments are closed.