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

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会
// i did not wanted to copy, just store the reference in the array, which turned out to be WRONG (it is not reference to the CLASS INSTANCE what is stored in the array, but rather reference to what variable with NAME $obj CURRENTLY holds).
// so we end up as shown below
}

for(
$i = 0; $i < 5;$i++) {
    echo
"Value:".$manyObjects[$i]->member."rn";
}   

/**
 * Output is :
 * Value:4
 * Value:4
 * Value:4
 * Value:4
 * Value:4

 * instead of expected

 * Value:0
 * Value:1
 * Value:2
 * Value:3
 * Value:4
 */

// If we change the value of $obj later in the script, all members would be changed in that moment

$obj = 1;
print_r($manyObjects);
/*
Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 1
)
*/
?>

Hope this spares someone few hours of time ;-)

Anonymous (23-Apr-2008 02:42)

 

 

 

To henrik at newdawn dot dk, 28-Oct-2007

No, it's not strange.
$this->$var['key'] tries to look up 'key' in the array $var and then use that for the property name. $this->{$var}['key'], on the other hand...

alexey at gmail dot com (25-Nov-2007 04:47)

 

 

 

I will describe how references interact with global variables.

Consider the following example. You create a DOM tree and then you use two functions. The first chooses an arbitrary tree element, while the second uses that element. Let us use a global variable as the means of communication between the two functions:

// global variable
var $dom_el;

test1(); // call first function
test2(); // call second function

function test1() {
global $dom_el, $Doc;

$dom_el = &$Doc->childNodes->item(0);
}

function test2() {
global $dom_el;

// $dom_el does not contain the reference! You cannot use it here.
// I am using PHP 4.4.6
}

If we assign a reference to the desired tree node in the first function then surprisingly the reference will disappear after the first function returns. That is, that reference is not saved in the global variable. Most likely, it is a feature of PHP 4 language. Specifically, I am using PHP 4.4.6. Thus, using a global variable to pass a reference from one function to another does not work.

However, if we save the reference as a field of an object, then the reference is preserved. Therefore, we need to wrap the global variable
in a class:

class Pointer {
var $i;

function Pointer() {
$this->i=null;
}

function set(&$_i) {
$this->i = &$_i;
}

function &get() {
return $this->i;
}
}

?>

Now the code looks like this:

$dom_el=new Pointer();

function test1() {
global $dom_el, $Doc;
$tmp = &$Doc->childNodes->item(0);
$dom_cur->set($tmp);
}

function test2() {
global $dom_el;

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