簡體   English   中英

在三元運算符中使用 return

[英]Using return in ternary operator

我正在嘗試在三元運算符中使用 return,但收到錯誤:

Parse error: syntax error, unexpected T_RETURN 

這是代碼:

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

這可能嗎?

謝謝!

這是正確的語法:

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

關。 你想要return condition?a:b

它在大多數語言中不起作用,因為return是一個語句(如ifwhile等),而不是可以嵌套在表達式中的運算符。 遵循相同的邏輯,您不會嘗試在表達式中嵌套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

不,這是不可能的,與以下相比,它也很令人困惑:

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

不,但是您可以為return語句使用三元表達式。

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

注意:這可能不是所需的邏輯。 我提供它作為一個例子。

撲通一聲,

如果你想用三元修改你的回報?

這是完全可能的。

在這個例子中,我有一個帶有參數數組的 function。 這個例子 function 用於解析用戶數組。 返回時,我有一個包含用戶 ID 和用戶名的數組。 但是如果我沒有任何用戶會發生什么?

<?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.
}

對不起我的英語不好,我是法國用戶哈哈。

ND。

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

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

希望有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM