Pergunta

I want to do something very simple:

if (getStatus()) {
    require_once('a.php');
} else {
    require_once('b.php');
}

function getStatus() {
    return true; //For the sake of this demo
}

How can this be rewritten using the ternary operator?

I assume something like this:

getStatus() ? require_once('a.php') : require_once('b.php');

But I can't work out the syntax. All examples I've seen use it = to something. e.g. x = y ? a : b;, but I don't want to use it in that way.

Is what I want to do even possible with it?

More Complex:

Can this also be expressed in ternary form?

if (websiteIsLive()) {
    setcookie("token", x, 0, '/', $_SERVER['HTTP_HOST'], true);
} else {
    setcookie("token", y, 0, '/');
}
Foi útil?

Solução

The arguments to the ternary operator, like any other operator, must be expressions. require_once is PHP syntax, it's not a function, so it can't be used within an expression. So you should use the ternary operator in the argument to require_once, which is an expression.

require_once (getStatus() ? 'a.php' : 'b.php');

For your extra request, you can do it with the ternary operator, but the result is not pretty, and IMHO harder to understand than the original:

call_user_func_array('setcookie', 
    websiteIsLive() ? 
        array("token", x, 0, '/', $_SERVER['HTTP_HOST'], true) :
        array("token", y, 0, '/'));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top