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:
<code class="php">class Foo {} function getFoo(Foo $f) {}</code>
Attempting to pass an array of Foo objects to getFoo will result in a fatal error:
<code class="php">Argument 1 passed to getFoo() must be an instance of Foo, array given</code>
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:
<code class="php">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'); } }</code>
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:
<code class="php">function getFoo(ArrayOfFoo $foos) { foreach ($foos as $foo) { // ... } }</code>
Now, passing an array of Foo objects to getFoo will work as expected.
Alternatively, the Haldayne library can be used to simplify the process:
<code class="php">class ArrayOfFoo extends \Haldayne\Boost\MapOfObjects { protected function allowed($value) { return $value instanceof Foo; } }</code>
This class provides built-in checks to ensure that only Foo objects are allowed in the array.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!