2016-04-26 8 views
12

私はphp7でリターンタイプのヒントを行うことができることを知っています。PHPの戻り値の型ヒント、オブジェクトまたはブール値?

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

} 

ここで、Userは返されるオブジェクトです。ユーザーが戻って、SQLに見つからない場合

しかし、代わりにユーザーオブジェクトの'false'ができます:

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

は、しかし、どのようなSQLがユーザーを見つけることができない場合は?ユーザーが存在しない場合、どのようにしてbooleanを返すことができますか?このシナリオでは、戻り値のヒントを無視する必要がありますか?

EDIT:「PHP 7のNullable戻り型」と私の質問はほぼ同じですが、私は2つの型のうちの1つを返す方法があるかどうかを尋ねて質問します。たとえば、オブジェクトが存在しない場合は、オブジェクトまたは文字列を返します。

+5

可能な重複を返すことができると言うドキュメントブロックを発行http://stackoverflow.com/questions/33608821/nullable-return-types-in- php7) –

+0

私の最初の反応は常に「例外を使う」ため、私はいつもこのような疑問を見つけます。そして、私は、例外はPHPのいわゆる "赤毛の踏み台"と同じように多くのことを覚えています。 –

+0

@ IgnacioVazquez-Abrams PHPは一般的に、一般的に例外に対する別のアプローチを採用しています。例えば、Pythonはそれらをほぼすべてのものに使用します。 PHPはそうではありません。例外的に、一般的にはかなり遅いので、どちらのケースにも役立ちません。 – bwoebi

答えて

12

あなたが話していることは、ユニオンタイプと呼ばれています。 (それが合格しますように見えるおろか)

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

このconsiderable discussion about it in Internalsは、すべてのPHP 7.1を対象としたが、まだアップ投票ではありませんあります。

あなたの問題はどうですか?私は、少なくとも今のところ、あなたのリターンをヒントしないと言います。ただ、(それは[PHP7でのNullable戻り値の型]のUserまたはfalse

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

すごく、ありがとう! – life

+0

または、あなたはException_NotFound()のような何かをスローすることができます –