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" );
有帮助吗?

解决方案

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"; });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top