Using return in ternary operator

你。 提交于 2019-11-26 16:59:23

问题


I'm trying to use return in a ternary operator, but receive an error:

Parse error: syntax error, unexpected T_RETURN 

Here's the code:

$e = $this->return_errors();
(!$e) ? '' : return array('false', $e);

Is this possible?

Thanks!


回答1:


This is the correct syntax:

return  !$e ? '' : array('false', $e);



回答2:


Close. You'd want return condition?a:b




回答3:


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. Following the same logic you wouldn't try to nest an if statement within an expression:

// 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.




回答4:


No it's not possible, and it's also pretty confusing as compared to:

if($e) {
    return array('false', $e);
}



回答5:


No. But you can have a ternary expression for the return statement.

return (!$e) ? '' : array('false', $e);

Note: This may not be the desired logic. I'm providing it as an example.




回答6:


No, that's not possible. The following, however, is possible:

$e = $this->return_errors();
return ( !$e ) ? '' : array( false, $e );

Hope that helps.




回答7:


Plop,

if you want modify your return with ternary ?

it's totally possible.

In this exemple, i have a function with array in parameters. This exemple function is used to parse users array. On return i have an array with user id and user username. 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.

N-D.



来源:https://stackoverflow.com/questions/6266334/using-return-in-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!