Dipendra Gurung Dipendra Gurung - 3 months ago 9
PHP Question

How to use php ternary operator in the parameter of a function?

I have a function,

abc(string $x, bool $y)


How can I use the ternary operator inside the function call expression? I tried this but gave

unexpected T_RETURN error

Code:

abc('Hello', return (1==1)?true:false);

Answer

In imperative languages like PHP, return is only used to return from a function. We call things like return statements, because they are things that one states in a function body.

On the other hand, things that have values or evaluate to values, like the number 2, or the expression 2 + 5 are called expressions.

You can think of return as a way to convert an expression (i.e., "hello, world!") into an action (i.e., return "hello,world!")

You can think of expressions like noun clauses (i.e., "a rock") and statements like actions (i.e., "give the rock to your boss").

In this case, PHP, like most imperative languages, expects you to only use expressions as arguments to functions.

Think about it -- what would it mean to pass an action as an argument to a function, or to add two actions together?

In the code you have, you want to call abc with the first argument set to 'Hello' and the second set to the value of the expression (1 == 1)?true:false. In this case, you don't need the return statement because (1==1)?true:false is already an expression, so you can just do:

abc('Hello', (1==1)?true:false);