Gall Annonim Gall Annonim - 3 months ago 7
PHP Question

PHP is that possible to add if statements when calling objects obj->sub1({if(foo==true) return foo; else return bar})

Im trying to create if statement inside $soap object, while typing its params.
my need is like that:
$soap->add($name,$something,$foo,$optionalarg,$optionalarg2);

this itself isnt too bad, but I need to change "optionalarg" for something else (to be precise "brak" ("none" in polish) )
making lots of cases dosent seem like good idea in that situation (it would be ton of that, and its not proper way to do that, I guess)

I know I could in theory prepare if for each optional arg before $soap, but Im looking for alternatives.

I tried googling,
I tried doing random-ish things (sometimes stuff just works but not in this case), like

$soap->add($name,$something,$foo,{if($enabled==true) $optarg else "brak"})

$soap->add($name,$something,$foo,{if($enabled==true) return $optarg else return "brak"})

$soap->add($name,$something,$foo,if($enabled==true) $optarg else "brak")

everything was throwing errors, so I gave up.

Answer

You are looking for the ternary operator:

$soap->add($name, $something, $foo, $enabled==true ? $optarg : "brak");

or in this specific case:

$soap->add($name, $something, $foo, $enabled ? $optarg : "brak");
                                    ^^^^^^^^ evaluated / cast to boolean

It takes 3 arguments and returns the second argument if the first evaluates to true and the third if the first argument evaluates to false.

Comments