Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP类型暗示允许Array或ArrayAccess_Php_Type Hinting_Union Types_Arrayaccess - Fatal编程技术网

PHP类型暗示允许Array或ArrayAccess

PHP类型暗示允许Array或ArrayAccess,php,type-hinting,union-types,arrayaccess,Php,Type Hinting,Union Types,Arrayaccess,是否可以允许实现ArrayAccess的数组或对象 例如: class Config implements ArrayAccess { ... } class I_Use_A_Config { public function __construct(Array $test) ... } $config = new Config; $lol = new I_Use_A_Config( (array) $config); 我希望能够传入数组或ArrayAccess 除了

是否可以允许实现ArrayAccess的数组或对象

例如:

class Config implements ArrayAccess {
    ...
}

class I_Use_A_Config
{
    public function __construct(Array $test)
    ...
}
$config = new Config;
$lol = new I_Use_A_Config( (array) $config);
我希望能够传入数组或ArrayAccess

除了手动检查参数类型之外,还有什么干净的方法可以做到这一点吗?

没有,没有“干净”的方法

数组
类型是基本类型。实现
ArrayAccess
接口的对象基于类,也称为复合类型。没有包含这两者的类型提示

因为您使用的是
ArrayAccess
数组,所以您可以将其强制转换。例如:

class Config implements ArrayAccess {
    ...
}

class I_Use_A_Config
{
    public function __construct(Array $test)
    ...
}
$config = new Config;
$lol = new I_Use_A_Config( (array) $config);

如果这不是一个选项(您希望按原样使用
Config
对象),那么只需删除类型提示并检查它是数组还是
ArrayAccess
。我知道你想避免那样,但这没什么大不了的。这仅仅是几行,当所有的话都说了,做了,就无关紧要了。

PHP8.0+

您可以使用
数组
数组访问
的并集

class I_Use_A_Config
{
    public function __construct(array|ArrayAccess $test)
    ...
}

这不是我所希望的答案,但向阵列施法实际上是个不错的主意。感谢这是一种糟糕的做法,客户端不应该做库可以做的事情。将对象强制转换到数组并不关心是否实现了ArrayAccess。AFAIK唯一会改变强制转换功能的是对ArrayObject类进行子类化。希望有一天能成功(显然与演员阵容无关,但与OP的问题有关);)这太可悲了:(此答案可能不满足所有情况。例如,我有一个调用getter而不是attributes的ArrayIterator,如果接收数组的函数尝试访问没有属性的getter,它将找不到它。在这种情况下,我将删除typehint,并使用
$test instanceof ArrayAccess或is\u array执行手动检查($test)