所以我知道我可以在 php7 中进行返回类型提示。我可以做一个对象返回提示:
function getUser($pdo, $username) : User
{
}
其中 User 是要返回的对象。
但是,如果在 SQL 中找不到用户,则返回 'false'
而不是 User 对象会给出:
Uncaught TypeError: Return value of UserFind::findUser() must be an instance of User, boolean returned
但是如果SQL找不到用户怎么办?如果用户不存在,如何返回 bool 值 false?在这种情况下,我是否应该忽略返回类型提示?
编辑:我查看了另一个问题“php 7 中的可空返回类型”,虽然我的问题几乎相同,但我想通过询问是否有办法返回两种类型之一来扩展我的问题。例如,如果对象不存在,则返回一个对象或一个字符串?
您所说的称为联合类型。有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:
- Successfully found results
- Successfully found no results
- There was an error
这都是针对 PHP 7.1 的,但尚未进行投票(更不用说看起来会通过了)。
那么你的问题呢?我想说,至少现在,不要输入提示你的返回。只需发出一个文档 block ,说明它可以返回 User
或 false
/**
* @param \PDO $pdo
* @param string $username
* @return User|false
*/