douao7937 2017-08-02 04:16
浏览 14
已采纳

为什么这个PHP对象会将项目附加到自身?

I'm new to OOP and seem to be stuck on something that i'm sure is very simple, but I don't understand what's happening.

The below example code:

class add_some {

    static $arr = array('a', 'b');

    static $new_arr = array();

    public static function iterate() {

        foreach (self::$arr as $v) {
            self::$new_arr[] = $v;
        }

    }

}

for ($i=0; $i < 3; $i++) {

    // instantiate the object
    $add_some = new add_some;

    // launch the method that copies items from $arr to $new_arr
    $add_some::iterate();

    echo '<pre>';
    print_r($add_some::$new_arr);
    echo "</pre>";

    unset($add_some);

}

Goes through a loop and adds the items which are in $arr to $new_arr, it basically copies all items from $arr to $new_arr

The code instantiates a new object and executes the method iterate() which copies items from $arr to $new_arr 3 times.

Each iteration creates a new object $add_some = new add_some; so each iteration should just produce:

Array
(
    [0] => a
    [1] => b
Array
(
    [0] => a
    [1] => b
)
Array
(
    [0] => a
    [1] => b
)

But for some reason the object keeps growing with each iteration.... And I have no idea why.. I tried destroying the object (unset) and not sure if I should be doing something else.

Array
(
    [0] => a
    [1] => b
)
Array
(
    [0] => a
    [1] => b
    [2] => a
    [3] => b
)
Array
(
    [0] => a
    [1] => b
    [2] => a
    [3] => b
    [4] => a
    [5] => b
)
  • 写回答

1条回答 默认 最新

  • drlh197610 2017-08-02 04:18
    关注

    You are calling the static method by use of the :: (Paamayim Nekudotayim), you should be using -> and not using a static function.

    Static means, keep this around globally, it is not instantiated each time you call new, it is static.

    You can for example call a static method like so:

    class MyClass {
      static function MyFunc() { echo 'Stuff'; }
    }
    
    MyClass::MyFunc()
    

    There is no need to (nor should you) create an instance of MyClass to call the static MyFunc.

    Each time you call iterate it is appending the global static array $arr

    The correct way to do this would be

    class add_some {
      private $x = 1;
      private $arr = array('a', 'b');
      public  $new_arr = array();
    
      public function iterate() {
        foreach ($this->arr as $v) {
            $this->new_arr[] = $v;
        }
      }
    }
    
    for ($i=0; $i < 3; $i++) {
      $add_some = new add_some();
      $add_some->iterate();
      print_r($add_some->new_arr);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行