免费邮箱 |加入收藏 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > PHP专区 > PHP技巧

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会
; // $d is 4
 
$b=array(&$a); // $b is a pointer to $a again
 
echo $a.$b[0].$c[0][0].$d; // outputs 9994
?>
These kind of pointers may even be passed to functions or returned from functions, copied and stored in multiple arrays/variables/objects, etc.

jasonpvp at gmail dot com (11-Jul-2008 07:16)

 

 

 

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)
  }
}

mpapec (27-Jun-2008 08:23)

 

 

 

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;
}

dnhuff at acm dot org (10-Jun-2008 03:40)

 

 

 

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.

Dave at SymmetricDesigns dot com (21-May-2008 02:24)

 

 

 

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[
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门