PHP Type hinting to allow Array or ArrayAccess

后端 未结 1 959
忘掉有多难
忘掉有多难 2021-01-04 06:46

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

For example:

class Config implements ArrayAccess {
    ...
}

class I_Use_         


        
1条回答
  •  攒了一身酷
    2021-01-04 07:34

    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.

    0 讨论(0)
提交回复
热议问题