PHP类型暗示允许Array或ArrayAccess
是否可以允许实现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 除了
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)
...
}
$test instanceof ArrayAccess或is\u array执行手动检查($test)