note 129095 added to class.arrayobject

From: Date: Sat, 09 Dec 2023 09:25:41 +0000
Subject: note 129095 added to class.arrayobject
Groups: php.notes 
Request: Send a blank email to php-notes+get-221049@lists.php.net to get a copy of this message
Note that this does not truly "allow objects to work as arrays" - an ArrayObject will not type-check as an array: <?php function gimme(array $a) { var_dump($a); } $a = new ArrayObject([1,2,3]); var_dump(is_array($a)); // false gimme($a); // Uncaught TypeError: gimme(): Argument #1 ($a) must be of type array, ArrayObject given ?> If you want something that type-checks both for arrays and ArrayObject, use the iterable pseudotype instead: <?php function gimme(iterable $a) { var_dump($a); } $a = [1,2,3]; var_dump(is_iterable($a)); // true var_dump($a instanceof iterable); // false (iterable is a pseudo-type and cannot be type-checked using instanceof) gimme($a); // works gimme(new ArrayObject($a)); // works ?> Notice the caveat here, that arrays will not type-check as instanceof iterable, because pseudotypes cannot be checked that way - if you need a run-time type-check, use is_iterable for the type-check instead. ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 83.91.127.54) ---- Manual Page -- https://php.net/manual/en/class.arrayobject.php Edit -- https://main.php.net/note/edit/129095 Del: integrated -- https://main.php.net/note/delete/129095/integrated Del: useless -- https://main.php.net/note/delete/129095/useless Del: bad code -- https://main.php.net/note/delete/129095/bad+code Del: spam -- https://main.php.net/note/delete/129095/spam Del: non-english -- https://main.php.net/note/delete/129095/non-english Del: in docs -- https://main.php.net/note/delete/129095/in+docs Del: other reasons-- https://main.php.net/note/delete/129095 Reject -- https://main.php.net/note/reject/129095 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221049) next »