首页 > 开发 > PHP > 正文

References and Aliases are Different Mechanisms (z

2024-05-04 22:56:44
字体:
来源:转载
供稿:网友
references and aliases are different mechanisms  
author:  zkarakaya  
date  14/03/2001  
<b>aliasing and referencing are completely different mechanisms in php.</b>
if you are java or c++ programmer, you must be careful when using
objects created on run-time.
<p>
lets see an example;
<pre>
<?
class myclass{
   var $mydata;
   var $outmanager;
    cfunction myclass($p){
      $this->mydata=$p;
      $this->outmanager = new myoutmanager($this);
   }
    cfunction display(){
      $this->outmanager->display();
   }
}
class myoutmanager{
   var $refobj;
    cfunction myoutmanager(&$obj){
      $this->refobj = &$obj;
   }
    cfunction display(){
      echo $this->refobj->mydata;
   }
}
$myvar = new myclass(10);
$myvar->mydata = 20;
$myvar->display();
?>
</pre>
what value be the output of this program code. many programmer will
say "20", but this is not correct. output is 10. why? because we have
created an instance of myclass type on the right hand side of assignment
operator, and gave an initial value of 10. in the constructor of myclass,
we have send the memory location of that newly created instance to another
object of type myoutmanager, and hold this value in $refobj. now the
reference count for this object is 1, which is $refobf property of
outmanager instance. lets continue the execution. constructor has finished
its job and returned to assignment operator. php4 now creates a new
reference named $myvar to newly created object. now the reference count
of that object is 2. be careful that $myvar is not an alies. so that when
you execute the next statement, which assigns a value 20 to its property
named $mydata, php4 creates a new instance of myclass type, copies
the contents of old one which is also referenced by its member outmanager.
and then changes the contents of mydata to 20.
<p>
>from now on you will have two different instance of type myclass.
our intend was not this. so to correct this problem, use alias
on the object creation statement, that is use;
<pre>
$myvar = &new myclass(10);
</pre>
this will solve the problem. so if you are c++ and java programmer,
you must be careful in writing php codes.
<p>
this description does not conflict with the information given in the
<a href="http://www.zend.com/zend/art/ref-count.php"> php 4: reference
counting and aliasing</a>
written by <a href="http://www.zend.com/comm_person.php?id=6" >andi
gutmans.</a>
<p>
ziya karakaya

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表