问题描述
是否可以允许Array或实现ArrayAccess的对象?
Is it possible to allow an Array or an object that implements ArrayAccess?
例如:
class Config implements ArrayAccess {
...
}
class I_Use_A_Config
{
public function __construct(Array $test)
...
}
我希望能够传递Array或ArrayAccess.
I want to be able to pass in either an Array or ArrayAccess.
除了手动检查参数类型外,还有一种干净的方法吗?
Is there a clean way to do this other than manually checking the parameter type?
推荐答案
不,没有干净"的方法.
No, there is no "clean" way of doing it.
array
类型是原始类型.实现ArrayAccess
接口的对象基于类,也称为复合类型.没有包含这两者的类型提示.
The array
type is a primitive type. Objects that implement the ArrayAccess
interface are based on classes, also known as a composite type. There is no type-hint that encompasses both.
由于您将ArrayAccess
用作数组,因此可以将其强制转换.例如:
Since you are using the ArrayAccess
as an array you could just cast it. For example:
$config = new Config;
$lol = new I_Use_A_Config( (array) $config);
如果这不是一个选项(您想按原样使用Config
对象),则只需删除类型提示并检查它是否为数组或ArrayAccess
.我知道您想避免这种情况,但这没什么大不了的.只是几行,而当一切都说完之后,就没什么了.
If that is not an option (you want to use the Config
object as it is) then just remove the type-hint and check that it is either an array or an ArrayAccess
. I know you wanted to avoid that but it is not a big deal. It is just a few lines and, when all is said and done, inconsequential.
这篇关于PHP类型提示以允许Array或ArrayAccess的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!