Question

In the javascript world we can run a function through a Ternary comparison, I wanted to see if this applies to PHP, it seems it does only to an extent.

This is not for production use nor will it be actually used. This is merely a topic to see PHP's in-depth extent of the ternary comparison.

<?
 $a = 1;
 $b = 1;

 function doThis($a){
     print "$a";
 }

 $a == $b ? ( doThis('TRUE') ):( print "FALSE" );
?>

The above code works perfectly, however, is it possible to run multiple functions and or operations within ()?

Such as?

 $a == $b ? ( doThis('TRUE'), doThis('THAT') ):( print "FALSE" );

or even?

$a == $b ? ( function(){ print "33"; doThis("TRUE") } ):( print "FALSE" );
Was it helpful?

Solution

You can have the ternary return a closure that would perform the requested function

 $func = $a==$b?function(){ print "33"; doThis("TRUE"); }:function(){ print "FALSE"}); );
 $func();

or borrowing from javascript you can create a IIFE (Immediately Invoked Function Expression)

 $a==$b?call_user_func(function(){print "33"; doThis("TRUE");}):
        call_user_func(function(){print "FALSE"; });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top