Type Hinting: Array of Objects
When passing an array of objects as an argument to a function, you may encounter an error if the argument type is not specified. For example, consider the following code:
class Foo {}
function getFoo(Foo $f) {}
Attempting to pass an array of Foo objects to getFoo will result in a fatal error:
Argument 1 passed to getFoo() must be an instance of Foo, array given
To overcome this issue, you can specify the argument type as an array of the desired object type using a custom class. For instance, an ArrayOfFoo class can be defined as follows:
class ArrayOfFoo extends \ArrayObject {
public function offsetSet($key, $val) {
if ($val instanceof Foo) {
return parent::offsetSet($key, $val);
}
throw new \InvalidArgumentException('Value must be a Foo');
}
}
This class ensures that only Foo objects can be assigned to its elements. The getFoo function can then be updated to accept an ArrayOfFoo argument:
function getFoo(ArrayOfFoo $foos) {
foreach ($foos as $foo) {
// ...
}
}
Now, passing an array of Foo objects to getFoo will work as expected.
Alternatively, the Haldayne library can be used to simplify the process:
class ArrayOfFoo extends \Haldayne\Boost\MapOfObjects {
protected function allowed($value) { return $value instanceof Foo; }
}
This class provides built-in checks to ensure that only Foo objects are allowed in the array.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3