> php教程 > php手册 > References and Aliases are Different Mechanisms (zkarakaya )

References and Aliases are Different Mechanisms (zkarakaya )

WBOY
풀어 주다: 2016-06-21 09:10:32
원래의
1035명이 탐색했습니다.

References and Aliases are Different Mechanisms  
Author:  zkarakaya  
Date  14/03/2001  
Aliasing and Referencing are completely different mechanisms in PHP.
If you are Java or C++ programmer, you must be careful when using
Objects created on run-time.


Lets see an example;

 <br> <br>class MyClass{ <br>   var $myData; <br>   var $outManager; <br>    cfunction MyClass($p){ <br>      $this->myData=$p; <br>      $this->outManager = new MyOutManager($this); <br>   } <br>    cfunction display(){ <br>      $this->outManager->display(); <br>   } <br>} <br> class MyOutManager{ <br>   var $refObj; <br>    cfunction MyOutManager(&$obj){ <br>      $this->refObj = &$obj; <br>   } <br>    cfunction display(){ <br>      echo $this->refObj->myData; <br>   } <br>} <br>$myvar = new MyClass(10); <br>$myvar->myData = 20; <br>$myvar->display(); <br>?> <br> 
로그인 후 복사

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.


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

 <br>$myvar = &new MyClass(10); <br>
로그인 후 복사

This will solve the problem. So if you are C++ and Java programmer,
you must be careful in writing PHP codes.


This description does not conflict with the information given in the
PHP 4: Reference
Counting and Aliasing

written by Andi
Gutmans.


Ziya Karakaya



관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿