duanchongchu5177 2012-09-10 20:16 采纳率: 0%
浏览 22
已采纳

执行函数后,对象的内容会发生变化

There are two objects of the same class:

$obj1 = new MyClass();
$obj2 = new MyClass();

Then I applied a function func to $obj2. However, once this function is executed, I noticed that the content of $obj1 has magically changed as well. I do not use any reference to $obj1 inside func. What might be the possible reasons of this problem? How do I solve it?

$obj2 = func($obj2,$vars);

I should say that I use other functions before func, and they also use $obj2 as an input. However, after their execution the content of $obj1 get not changed.

P.S. When I debug this code in Zend Studio and go inside func, Watch list Expressions says that $obj1 = null, but I think it's fine, because func is saved in a different PHP file.

  • 写回答

1条回答 默认 最新

  • doukuanjing5404 2012-09-10 20:23
    关注

    Consider this:

    class MyClass
    {
      public static $value;
    
      public function test( $testvalue )
      {
        self::value = $testvalue;
      }
    }
    
    $obj1 = new MyClass();
    $obj2 = new MyClass();
    
    $obj1->test( 123 );
    
    echo $obj2::value; // this will echo 123!!
    

    There are no changes to made to $obj2, only to $obj1. The static causes the var to loose its object contents, and becomes 'global' to all objects.

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大