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

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会


note, if you want to use a shortcut variable to modify the original object you must include the ampersand (&) to reference the variable, otherwise if you used this line of code

//start

$tempObj = $obj1 -> obj2 -> obj3;

//end

any changes you make to $tempObj will not change the original object and may compromise the object structure, not to mention that it takes up extra memory.  however, if you are just using the shortcut variable for read-only purposes, not using a reference wont cause any problems.

another alternative in programming languages is the 'with' structure as seen below

//start

with($obj1 -> obj2 -> obj3) {
    varX = 0;
    varY = 0;
    functionX();
    functionY();
}

//end

however, i don't expect this will work because as far as i've seen the 'with' structure is not supported in php.

nathan (06-Apr-2004 01:53)

 

 

 

On the post that says php4 automagically makes references, this appears to *not* apply to objects:

http://www.php.net/manual/en/language.references.whatdo.php

"Note:  Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues."

iryoku at terra dot es (31-Mar-2004 02:22)

 

 

 

You should have in mind that php4 keep assigned variables "automagically" referenced until they are overwritten. So the variable copy is not executed on assignment, but on modification. Say you have this:

$var1 = 5;
$var2 = $var1; // In this point these two variables share the same memory location
$var1 = 3; // Here $var1 and $var2 have they own memory locations with values 3 and 5 respectively

Don't use references in function parameters to speed up aplications, because this is automatically done. I think that this should be in the manual, because it can lead to confusion.

More about this here:
http://www.zend.com/zend/art/ref-count.php

developer at sirspot dot com (04-Feb-2004 02:30)

 

 

 

Since references are more like hardlinks than pointers, it is not possible to change a reference to an object by using that same reference.  For example:

The following WILL NOT WORK as expected and may even crash the PHP interpreter:

$object =& $object->getNext();

However, by changing the previous statement to use a temporary reference, this WILL WORK:

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