0

I have code like this:

$finalResult = true;

$finalResult = $finalResult && function_01();
// some code here
$finalResult = $finalResult && function_02();
// some many lines of code here
$finalResult = $finalResult && function_XX();


And I'm looking for a way how to shorten the code (just for a human-readibility reasons) to something like:

$finalResult = true;

$finalResult &&= function_01();
// some code here
$finalResult &&= function_02();
// some many lines of code here
$finalResult &&= function_XX();

But of course this doesn't work and operator &= is not for boolean values, but for binary.

How should I do this ?
Thanks.

Enriqe
  • 567
  • 1
  • 6
  • 22

3 Answers3

1
$names = array('function01','function02'...);
$result = true;
foreach($names as $caller)
{
  $result = $result && $caller();
}

otherwise instead of $caller() you could look for call_user_func ( http://us3.php.net/call_user_func )

it's not really fantastic, but it's shorter :/ not a big deal

edit: uhm... i guess that after your edit this solution is not more functional... should i delete it ?

I would also reconsider the logic of your code by adding a class that makes these checks: if all the checking logic is in a class whose purpose is just that you could surely benefit of readability

Stormsson
  • 1,391
  • 2
  • 16
  • 29
  • Hmmm those functions must be called on those lines where they are. Rest of the code needs their results. I will think about that `call_user_func` but I hoped for something simple and easy just as `+=` . – Enriqe Nov 03 '13 at 13:10
1

Stormsson's but improved - finish as soon as you know the result:

$names = array( 'function01','function02'... );
$result = true;

foreach( $names as $caller )
{
    if ( $result == false ) break; // short circuit

    $ret = $caller()
    if ( $ret == false )
    {
        $result = false;
        break; // short circuit
    }

    $result = $result && $ret;
}
Artur
  • 7,038
  • 2
  • 25
  • 39
0

OK, after all it seems I will not get it any simpler than original.

For those of you who don't understand why I want to have it in some "short" form - only reason was to have it shorter and nicer. Just the same reason why there is possibility to write $a += 3 just for beauty.

Anyway, thanks to everybody :)

Enriqe
  • 567
  • 1
  • 6
  • 22