Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Type hinting to allow Array or ArrayAccess

Is it possible to allow an Array or an object that implements ArrayAccess?

For example:

class Config implements ArrayAccess {
    ...
}

class I_Use_A_Config
{
    public function __construct(Array $test)
    ...
}

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?

like image 464
Supericy Avatar asked Feb 11 '13 05:02

Supericy


2 Answers

No, there is no "clean" way of doing it.

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.

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);

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.

like image 196
Sverri M. Olsen Avatar answered Sep 28 '22 03:09

Sverri M. Olsen


PHP 8.0+

You can use union of array and ArrayAccess.

class I_Use_A_Config
{
    public function __construct(array|ArrayAccess $test)
    ...
}
  • https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.union
  • https://wiki.php.net/rfc/union_types
like image 35
Hendrik Avatar answered Sep 28 '22 02:09

Hendrik