类型提示 - 指定一个对象数组 [英] Type hinting - specify an array of objects

查看:49
本文介绍了类型提示 - 指定一个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将参数类型指定为数组?假设我有一个名为Foo"的类:

How can I specify the argument type as an array? Say I have a class named 'Foo':

class Foo {}

然后我有一个接受该类类型作为参数的函数:

and then I have a function that accepts that class type as an argument:

function getFoo(Foo $f) {}

当我传入一个 'Foo's 数组时,我收到一个错误,说:

When I pass in an array of 'Foo's I get an error, saying:

可捕获的致命错误:传递给 getFoo() 的参数 1必须是 Foo 的实例,给定数组

Catchable fatal error: Argument 1 passed to getFoo() must be an instance of Foo, array given

有没有办法解决这个问题?也许像

Is there a way to overcome this issue? maybe something like

function getFoo(Foo $f[]) {}

推荐答案

如果您想确保您正在使用Foo 数组"并且您想确保方法接收Foo 数组",您可以:

If you want to ensure you are working with "Array of Foo" and you want to ensure methods receive "Array of Foo", you can:

class ArrayOfFoo extends \ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Foo) {
            return parent::offsetSet($key, $val);
        }
        throw new \InvalidArgumentException('Value must be a Foo');
    }
}

然后:

function workWithFoo(ArrayOfFoo $foos) {
    foreach ($foos as $foo) {
        // etc.
    }
}

$foos = new ArrayOfFoos();
$foos[] = new Foo();
workWithFoo($foos);

秘诀在于您定义了foo 数组"的新类型",然后使用类型提示保护传递该类型".

The secret sauce is that you're defining a new "type" of "array of foo", then passing that "type" around using type hinting protection.

Haldayne 库 会处理用于成员资格要求检查的样板(如果您不这样做)不想自己动手:

The Haldayne library handles the boilerplate for membership requirement checks if you don't want to roll your own:

class ArrayOfFoo extends \Haldayne\Boost\MapOfObjects {
    protected function allowed($value) { return $value instanceof Foo; }
}

(完全公开,我是 Haldayne 的作者.)

历史注释:RFC 数组 早在 2014 年就提出了此功能.RFC 被拒绝4 是和 16 否.这个概念最近重新出现在内部列表,但投诉与针对原始 RFC 征收的费用大致相同:添加此检查将 显着影响性能.

Historical note: the Array Of RFC proposed this feature back in 2014. The RFC was declined with 4 yay and 16 nay. The concept recently reappeared on the internals list, but the complaints have been much the same as levied against the original RFC: adding this check would significantly affect performance.

这篇关于类型提示 - 指定一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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