PHP返回类型提示,对象还是布尔值? [英] PHP return type hinting, object OR a boolean?

查看:85
本文介绍了PHP返回类型提示,对象还是布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道我可以在php7中返回类型提示.我可以使用以下方法做一个对象返回提示:

So I know that I can do return type hinting in php7. I can do an object return hint with:

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

}

其中User是要返回的对象.

where User is the object being returned.

但是,如果在SQL中找不到用户,则返回'false'而不是User对象将给出:

However, if the user isn't found in the SQL, returning 'false' instead of a User object gives:

未捕获的TypeError:UserFind :: findUser()的返回值必须是User的实例,返回的是布尔值

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

但是,如果SQL找不到用户该怎么办?如果用户不存在,如何返回布尔值,false?在这种情况下,我应该忽略返回类型提示吗?

But what if the SQL can't find the user? How can I return a boolean, false, if the user doesn't exist? Should I just ignore return type hinting in this scenario?

我看了另一个问题,"php 7中的空返回类型",尽管我的问题几乎相同,但我想通过询问是否有一种方法可以返回两种类型中的一种来扩展我的问题.例如,如果对象不存在,则返回一个对象或一个字符串?

I looked at the other question, 'Nullable return types in php 7' and while my question is almost identical, I want to extend my question by asking if there would ever be a way to return one of two types. For example return an object or a string if the object is nonexistant?

推荐答案

您所说的称为联合类型.在内部构件中有对此问题的详细讨论

What you're talking about is called a Union Type. There's considerable discussion about it in Internals

此RFC提出了为参数或返回类型定义多种可能类型的能力,并将其称为联合类型".如果值将通过联合的任何一个成员,则该值通过联合类型的类型检查.两种或多种类型之间都放置了一个竖线(OR).

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.

这是一个参数的示例,该参数接受数组或Traversable且不接受其他类型:

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. 成功找到结果
  2. 未找到任何结果
  3. 出现错误
  1. Successfully found results
  2. Successfully found no results
  3. There was an error

这全部针对PHP 7.1,但尚未投票(更不用说看起来会通过).

This is all targeted at PHP 7.1 but isn't up for a vote yet (let alone looking like it will pass).

那您的问题呢?我要说,至少到目前为止,不要键入提示您的回报.只需发出一个说它可以返回Userfalse

So what about your issue? I would say, at least for now, don't type hint your return. Just issue a doc block that says it can return User or false

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

这篇关于PHP返回类型提示,对象还是布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆