• 技术文章 >php教程 >php手册

    References and Aliases are Different Mechanisms (zkarakaya )

    2016-06-21 09:10:32原创544
    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;

     
    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();
    ?>

    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;

     
    $myvar = &new MyClass(10);

    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



    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:nbsp this gt MyClass the
    上一篇:PHP4之COOKIE支持详解[转自奥索] 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • PHP实现通过get方式识别用户发送邮件的方法• Codeigniter框架实现获取分页数据和总条数的方法• php将csv文件导入到mysql数据库的方法,• php批量添加数据与批量更新数据的实现方法,php添加数据• PHP弹出提示框并跳转到新页面(重定向)
    1/1

    PHP中文网