It looks this works in PHP.
function test(a) {
a && (console_log("somthing") xor executeOtherFunction());
}
I think PHP is able to convert everything to bool without errors.
Question
In Javascript we can do this by following code:
function test(a) {
a && (console.log("somthing"), executeOtherFunction());
}
this code above is shorthand of:
function test(a){
if(a){
console.log("something");
executeOtherFunction()
}
}
Is possible to get this working for PHP?
I don't mean that use console.log
in PHP, just want use same thing in PHP.
La solution
It looks this works in PHP.
function test(a) {
a && (console_log("somthing") xor executeOtherFunction());
}
I think PHP is able to convert everything to bool without errors.
Autres conseils
In PHP, there is also short-circuit in condition evaluation.
With an AND
(or &&
), the evaluation will stop as soon as a false
value is encountered.
But, the comma ,
operator is not supported by PHP. So, you can't execute two expressions by separating them with a ,
. It is only allowed, as a syntactic sugar, in a for loop:
for ($a = 2, $b = 4; $a < 3; $a++)
^
This construction is also often used with or
keyword:
someAction() or log("someAction() execution failed");
This will log the error only if someAction()
returns false
.
As Guillaume Poussel said, PHP knows short circuit in condition evaluation, but not chaining of code blocks via ,
.
If you are willing to really abuse PHP's weak typing system, you could use something like this:
if ($a && function1() . function2() ) ;
^ concatenate the results of the functions as strings
obviously this would only work if you don't need the return values of the functions.
disclaimer: I don't recommend the use of this in production code, but it is an interesting thought experiment