S
S
Stanislav2016-12-16 11:02:19
PHP
Stanislav, 2016-12-16 11:02:19

What is the most concise and understandable way to pass one of two variables to one function argument, which can be either an array or a logical expression?

Hello. An interesting question has arisen. There is a certain function, it has conditionally one argument:

function f($a) {
...
}

This function can be called in several places in the code, but the choice of a variable that will be passed to the argument of this function depends only on the variable itself. In this case, variables can be either an array or, for example, an object, or take a boolean value. That is, some redundant code appears:
// заранее известно, что одна из переменных будет массивом/объектом, а другая - true/false
if ($x) {f($x)}
else if ($y) {f($y)}

However, I would like to see something like this:
f($x || $y);
But here the conversion to types takes place and as a result we get a boolean value in the argument in the function body, namely true (it will always be there, since the previous code ensures that one of the variables is an array / an object). Attention, the question is: is it possible to have some other short notation that allows you to implement what is described just as beautifully? Apart from using the short form of the "if else" statement, of course.
Example for testing at phpfiddle.org .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem Gapchenko, 2016-12-16
@artemgapchenko

Perhaps you are approaching the problem in the wrong way. I would get rid of the function that takes a boolean on Mondays, an array on Tuesdays, and an object on the rest of the week, since this function takes on too much responsibility, and would switch instead to three different functions, the first of which takes a boolean argument, the second takes an array, and the third takes an object.
The code is written not only to be executed, but also to be read by other developers, and such a feature is clearly not conducive to the speed of studying the code and making changes to it.

S
surgat, 2016-12-16
@surgat

Maybe the ternary operator
will suit you. And the short version
is f($x ?: $y)
In this case, if $x is TRUE, then $x and $y will be passed to f otherwise.
Examples

true ?: 'test' - будет true
false ?: 'test' - будет 'test'
'' ?: true - будет true
'test' ?: true - будет 'test'

// Комбинирование
false ?: [] ?: 'test' - будет 'test'

A
Arman, 2016-12-16
@Arik

$x ? f($x) : ($y ? f($y) : null);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question