2016-04-26 33 views
12

Quindi so che posso fare restituire il tipo di suggerimento in php7. Posso fare un rendimento suggerimento oggetto con:PHP tipo di ritorno suggerimento, oggetto O un booleano?

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

} 

in cui l'utente è l'oggetto che viene restituito.

Tuttavia, se l'utente non si trova nella SQL, tornando 'false' invece di un oggetto utente dà:

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

Ma cosa succede se l'SQL non può trovare l'utente? Come posso restituire un valore booleano, falso, se l'utente non esiste? Devo semplicemente ignorare il tipo di suggerimento di ritorno in questo scenario?

MODIFICA: ho esaminato l'altra domanda, 'Nullable return types in php 7' e mentre la mia domanda è quasi identica, voglio estendere la mia domanda chiedendo se ci sarebbe mai stato un modo per restituire uno di due tipi . Ad esempio restituire un oggetto o una stringa se l'oggetto non esiste?

+5

Eventuali duplicati di [tipi restituiti Nullable in PHP7] (http://stackoverflow.com/questions/33608821/nullable-return-types-in- php7) –

+0

Trovo sempre domande strane, perché la mia prima reazione è sempre "usa un'eccezione". E poi ricordo che le eccezioni sono, come molte altre cose, il cosiddetto "figliastro dai capelli rossi" in PHP. –

+0

@ IgnacioVazquez-Abrams PHP utilizza generalmente un altro approccio alle eccezioni in generale. Ad esempio Python li usa per quasi tutto. PHP no. Anche le eccezioni sono abbastanza lente in generale, non aiuta neanche il caso. – bwoebi

risposta

12

Quello di cui parli si chiama Union Type. C'è 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

Questo è tutto mirato a PHP 7.1, ma non è su per un voto ancora (per non parlare che sembra passerà).

Quindi, per quanto riguarda il problema? Direi, almeno per ora, non digitare il suggerimento per il tuo ritorno. Basta rilasciare un blocco doc che dice che può tornare User o false

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

fantastico, grazie! – life

+0

Oppure potresti lanciare un messaggio come Exception_NotFound() –