note 111999 added to class.arrayaccess

From: Date: Sat, 20 Apr 2013 07:09:08 +0000
Subject: note 111999 added to class.arrayaccess
Groups: php.notes 
Request: Send a blank email to php-notes+get-194575@lists.php.net to get a copy of this message
Sadly you cannot assign by reference with the ArrayAccess (at least in PHP 5.3.23) It's too bad there is no syntax for optionally passing variables by reference to functions (a feature in retro PHP). That option would have let ArrayAccess fully mimic the functionality of normal array assignments: <?php $var = 'hello'; $arr = array(); $arr[0] = $var; $arr[1] = &$var; $var = 'world'; var_dump($arr[0], $arr[1]); // string(5) "hello" // string(5) "world" ?> Declaring "function offsetSet($offset, &$value)" will cause a fatal error. So to assign by ref you can use an ugly function call, for example: <?php class obj implements ArrayAccess { // ... ArrayAccess example code ... public function &offsetSetRef($offset, &$value) { if (is_null($offset)) { $this->container[] = &$value; } else { $this->container[$offset] = &$value; } return $value; // should return in case called within an assignment chain } } $var = 'hello'; $obj = new obj(); $obj[0] = $var; //$obj[1] = &$var; // Fatal error: Cannot assign by reference to overloaded object $obj->offsetSetRef(1, $var); // the work around $var = 'world'; var_dump($obj[0], $obj[1]); // string(5) "hello" // string(5) "world" ?> ---- Server IP: 69.147.83.199 Probable Submitter: 68.144.196.167 ---- Manual Page -- http://php.net/manual/en/class.arrayaccess.php Edit -- https://master.php.net/note/edit/111999 Del: integrated -- https://master.php.net/note/delete/111999/integrated Del: useless -- https://master.php.net/note/delete/111999/useless Del: bad code -- https://master.php.net/note/delete/111999/bad+code Del: spam -- https://master.php.net/note/delete/111999/spam Del: non-english -- https://master.php.net/note/delete/111999/non-english Del: in docs -- https://master.php.net/note/delete/111999/in+docs Del: other reasons-- https://master.php.net/note/delete/111999 Reject -- https://master.php.net/note/reject/111999 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#194575) next »