将一组接口传递给一个函数? [英] Pass an array of interfaces into a function?

查看:107
本文介绍了将一组接口传递给一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,因为接口的好处可以通过传递参数来提及接口名称,例如

In PHP since the interface benefits can used by passing as parameter mentioning the Interface name something like

public function foo (Abc $abc){}

其中Abc是一个接口。但是我如何传递这些接口的数组?

where Abc is an interface.But how do I pass an array of these interfaces?

请注意,这不是类,而是接口,只有获得接口的方法是通过类型提示传递函数

Please note this not class but interface and only way to get advantage of interface is passing as function with type hinting

推荐答案

在PHP 5.6+中你可以这样做:

In PHP 5.6+ you could do something like this:

function foo(Abc ...$args) {

}

foo(...$arr);

foo()需要可变金额 abc 类型的参数,并通过调用 foo(... $ arr)解压缩 $ arr 进入参数列表。如果 $ arr 包含除 abc 实例以外的任何内容,则会引发错误。

foo() takes a variable amount of arguments of type Abc, and by calling foo(...$arr) you unpack $arr into a list of arguments. If $arr contains anything other than instances of Abc an error will be thrown.

这有点'hacky',但它是在PHP中获取数组类型提示的唯一方法,而不会放下一些额外的代码。

This is a little 'hacky', but it's the only way to get type hinting for an array in PHP, without putting down some extra code.

这篇关于将一组接口传递给一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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