; $b=array(&$a); echo $a.$b[0].$c[0][0].$d; ?>
These kind of pointers may even be passed to functions or returned from functions, copied and stored in multiple arrays/variables/objects, etc.
To change values in a multi-dimensional array while looping through:
$var=array('a'=>array(1,2,3),'b'=>array(4,5,6));
foreach ($var as &$sub) {
foreach ($sub as &$element) {
$element=$element+1;
}
}
var_dump($var);
------------------------------
produces:
------------------------------
array(2) {
["a"]=>
array(3) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(4)
}
["b"]=>
array(3) {
[0]=>
int(5)
[1]=>
int(6)
[2]=>
int(7)
}
}
It's strange that function definition AND call to the same function must have "&" before them.
$arr = array();
$ref =& oras($arr['blah'], array());
$ref []= "via ref";
print_r($arr);
/* result
Array
(
[blah] => Array
(
[0] => via ref
)
)
*/
// perl like ||=
function &oras (&$v, $new) {
$v or $v = $new;
return $v;
}
This is discussed before (below) but bears repeating:
$a = null; ($a =& null; does not parse) is NOT the same as unset($a);
$a = null; replaces the value at the destination of $a with the null value;
If you chose to use a convention like $NULL = NULL;
THEN, you could say $a =& $NULL to break any previous reference assignment to $a (setting it of course to $NULL), which could still get you into trouble if you forgot and then said $a = '5'. Now $NULL would be '5'.
Moral: use unset when it is called for.
Another example of something to watch out for when using references with arrays. It seems that even an usused reference to an array cell modifies the *source* of the reference. Strange behavior for an assignment statement (is this why I've seen it written as an =& operator? - although this doesn't happen with regular variables).
<?php
$array1 = array(1,2);
$x = &$array1[
9/24 首页 上一页 7 8 9 10 11 12 下一页 尾页 |