dota220141003 2013-04-02 15:39
浏览 26
已采纳

将一个类的实例分配给php中的新对象

Following is an example in manual:

<?php

    $instance = new SimpleClass();
    $assigned   =  $instance;
    $reference  =& $instance;

    $instance->var = '$assigned will have this value';
    $instance = null; // $instance and $reference become null

    var_dump($instance);
    var_dump($reference);
    var_dump($assigned);
 ?>

I cannot understand the result :

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

Anyone can tell me the answer, I think the three var point the same instance.

  • 写回答

1条回答 默认 最新

  • doukongyong44772 2013-04-02 15:44
    关注
    $instance = new SimpleClass(); // create instance
    $assigned   =  $instance; // assign *identifier* to $assigned
    $reference  =& $instance; // assign *reference* to $reference 
    
    $instance->var = '$assigned will have this value';
    $instance = null; // change $instance to null (as well as any variables that reference same)
    

    Assigning via reference and identifier are different. From the manual:

    One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

    A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

    Check out this answer for more info.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画