Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to ensure you are working with "Array of Foo" and you want to ensure methods receive "Array of Foo", you can:</p> <pre><code>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></pre> <p>then:</p> <pre><code>function workWithFoo(ArrayOfFoo $foos) { foreach ($foos as $foo) { // etc. } } $foos = new ArrayOfFoos(); $foos[] = new Foo(); workWithFoo($foos); </code></pre> <p>The secret sauce is that you're defining a new "type" of "array of foo", then passing that "type" around using type hinting protection.</p> <hr> <p>The <a href="http://haldayne-docs.readthedocs.org/en/latest/boost/" rel="nofollow noreferrer">Haldayne library</a> handles the boilerplate for membership requirement checks if you don't want to roll your own:</p> <pre><code>class ArrayOfFoo extends \Haldayne\Boost\MapOfObjects { protected function allowed($value) { return $value instanceof Foo; } } </code></pre> <p><em>(Full-disclosure, I'm the author of Haldayne.)</em></p> <hr> <p>Historical note: the <a href="https://wiki.php.net/rfc/arrayof" rel="nofollow noreferrer">Array Of RFC</a> proposed this feature back in 2014. The RFC was declined with 4 yay and 16 nay. The concept recently <a href="https://marc.info/?l=php-internals&amp;m=150896437718050&amp;w=2" rel="nofollow noreferrer">reappeared on the internals list</a>, but the complaints have been much the same as levied against the original RFC: adding this check would <a href="http://rwec.co.uk/blog/2016/10/towards-a-consistent-php-type-checking-system/" rel="nofollow noreferrer">significantly effect performance</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload