Reputation: 567
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.
Upvotes: 0
Views: 165
Reputation: 567
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 :)
Upvotes: 0
Reputation: 7257
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;
}
Upvotes: 1
Reputation: 1541
$names = array('function01','function02'...);
$result = true;
foreach($names as $caller)
{
$result = $result && $caller();
}
otherwise instead of $caller() you could look for call_user_func ( https://www.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
Upvotes: 1