PHP 返回类型提示,对象或 bool 值?

标签 php php-7 type-hinting

<分区>

所以我知道我可以在 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:

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

这都是针对 PHP 7.1 的,但尚未进行投票(更不用说看起来会通过了)。

那么你的问题呢?我想说,至少现在,不要输入提示你的返回。只需发出一个文档 block ,说明它可以返回 Userfalse

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

关于PHP 返回类型提示,对象或 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36873567/

相关文章:

PHP MySQL 数组 while ==

php - 如何从页面内以编程方式访问网站的 url

PHP7 + Symfony 3.1.0 + Vagrant : Failed to write session data

php - 变量方法的变量属性

python - 在 python 3.9+ 中,如何使用省略号为内置元组类型编写类型别名? (mypy 错误?)

php - 如何通过按钮/变量增加天数?

php - OSX El Capitan 永久更改 PHP 版本

python - Python 类型提示(注释)是否会导致一些运行时影响?

python - Python 3.6 中的相互递归类型,使用命名元组语法

php - 如何使用php从另一个表中获取一个表的字段值