2011-06-07 117 views
15

回報我試圖使用三元操作符的回報,但收到一個錯誤:使用在三元運算符PHP

Parse error: syntax error, unexpected T_RETURN 

下面的代碼:

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

這可能嗎?

謝謝!

回答

6

它在大多數語言中不起作用,因爲return是一個語句(如if,while等),而不是可以嵌套在表達式中的運算符。按照同樣的邏輯,你就不會嘗試拼圖的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); 

它不會對breakcontinue正常工作。

2

不,這是不可能的,而且它也非常令人迷惑相比:

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

這是正確的語法:

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

我不認爲這是OP的例子的預期結果。這將在兩種情況下都會返回,而OP可能只是在其中一種情況下詢問如何返回。 – 2011-06-07 14:03:29

+1

沒錯,但它不會那樣工作。因爲它是一個聲明並且不能嵌套在一個三元組中,所以總是會返回一個三元組。 – CommandZ 2014-02-22 03:10:36

0

不,那是不可能的。但是,以下是可能的:

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

希望有所幫助。

6

關閉。 你想要return condition?a:b

+0

+1作爲新用戶。不要忘記格式化你的代碼:) – 2011-06-07 14:03:41

1

不,但你可以有一個return陳述的三元表達式。

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

注:這可能不是所期望的邏輯。我提供它作爲一個例子。