2016-04-26 87 views
12

所以我知道我可以在php7中做返回類型提示。我可以做一個對象返回提示:PHP返回類型提示,對象或布爾?

function getUser($pdo, $username) : User 
{ 

} 

其中用戶是被返回的對象。

然而,如果用戶沒有在SQL中發現,返回'false'而不是用戶對象給出:

Uncaught TypeError: Return value of UserFind::findUser() must be an instance of User, boolean returned

但是,如果SQL無法找到用戶?如果用戶不存在,我該如何返回一個布爾值,假?我應該忽略這種情況下的返回類型暗示嗎?

編輯:我看着另一個問題,'在PHP 7可空返回類型',雖然我的問題幾乎相同,我想通過問是否會有一種方式來返回兩種類型。例如,如果對象不存在,則返回一個對象或字符串?

+5

[在PHP7可空返回類型(的可能的複製http://stackoverflow.com/questions/33608821/nullable-return-types-in- php7) –

+0

我總是發現這樣的問題很奇怪,因爲我的第一反應總是「使用例外」。然後我記得,例外情況與其他許多事情一樣,是PHP中所謂的「紅頭髮的繼子女」。 –

+0

@ IgnacioVazquez-Abrams PHP通常採用另一種方法來處理異常。 Python例如幾乎所有東西都使用它們。 PHP不。一般而言,例外情況相當緩慢也無助於案例。 – bwoebi

回答

12

你在說什麼叫做聯合類型。有considerable discussion about it in Internals

This RFC proposes the ability to define multiple possible types for a parameter or return type and calls them 「union types」. A value passes the type-check for a union type if the value would pass any one of the members the union. A vertical bar (OR) is placed between each of the two or more types.

Here is an example of a parameter accepting either an array or a Traversable and no other types:

function (Array | Traversable $in) { 
    foreach ($in as $value) { 
     echo $value, PHP_EOL; 
    } 
} 

There can be more than two types in the union. As an example, it is somewhat common for a routine that interacts with a database to have one of three results:

  1. Successfully found results
  2. Successfully found no results
  3. There was an error

這一切都是針對PHP 7.1,但不要爲一票,但(更別說看起來像它會通過)。

那麼你的問題呢?至少在現在,我會說,不要提示你的回報。只是發出一個文檔塊,指出它可以返回Userfalse

/** 
* @param \PDO $pdo 
* @param string $username 
* @return User|false 
*/ 
+0

真棒,謝謝! – life

+0

或者你可以拋出一些像Exception_NotFound() –