Voting

The Note You're Voting On

ivan dot dossev at gmail dot com
12 years ago
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"

?>

<< Back to user notes page

To Top