[英]Using return in ternary operator
I'm trying to use return in a ternary operator, but receive an error:我正在尝试在三元运算符中使用 return,但收到错误:
Parse error: syntax error, unexpected T_RETURN
Here's the code:这是代码:
$e = $this->return_errors();
(!$e) ? '' : return array('false', $e);
Is this possible?这可能吗?
Thanks!谢谢!
This is the correct syntax:这是正确的语法:
return !$e ? '' : array('false', $e);
Close.关。 You'd want
return condition?a:b
你想要
return condition?a:b
It doesn't work in most languages because return
is a statement (like if
, while
, etc.), rather than an operator that can be nested in an expression.它在大多数语言中不起作用,因为
return
是一个语句(如if
、 while
等),而不是可以嵌套在表达式中的运算符。 Following the same logic you wouldn't try to nest an if
statement within an expression:遵循相同的逻辑,您不会尝试在表达式中嵌套
if
语句:
// invalid because 'if' is a statement, cannot be nested, and yields no result
func(if ($a) $b; else $c;);
// valid because ?: is an operator that yields a result
func($a ? $b : $c);
It wouldn't work for break
and continue
as well.它不适用于
break
和continue
。
No it's not possible, and it's also pretty confusing as compared to:不,这是不可能的,与以下相比,它也很令人困惑:
if($e) {
return array('false', $e);
}
No. But you can have a ternary expression for the return
statement.不,但是您可以为
return
语句使用三元表达式。
return (!$e) ? '' : array('false', $e);
Note: This may not be the desired logic.注意:这可能不是所需的逻辑。 I'm providing it as an example.
我提供它作为一个例子。
Plop,扑通一声,
if you want modify your return with ternary?如果你想用三元修改你的回报?
it's totally possible.这是完全可能的。
In this exemple, i have a function with array in parameters.在这个例子中,我有一个带有参数数组的 function。 This exemple function is used to parse users array.
这个例子 function 用于解析用户数组。 On return i have an array with user id and user username.
返回时,我有一个包含用户 ID 和用户名的数组。 But what happens if I do not have any users?
但是如果我没有任何用户会发生什么?
<?php
public funtion parseUserTable(array $users) {
$results = [];
foreach ($users as $user) {
$results[$users['id']] = $user['username'];
}
return $results ?: array('false', $e, "No users on table."); // Ternary operator.
}
Sorry for my bad english, i'm french user haha.对不起我的英语不好,我是法国用户哈哈。
ND. ND。
No, that's not possible.不,那是不可能的。 The following, however, is possible:
但是,以下情况是可能的:
$e = $this->return_errors();
return ( !$e ) ? '' : array( false, $e );
Hope that helps.希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.