douduan1953 2014-07-21 12:03
浏览 42

在Class中将Class对象创建为PHP中的数组var

I'm trying to add new PHP Objects to an Array inside a Class. It works for 2 entries but then after adding 1 more the whole array gets destructed.

public $players = array();

This is the Code where I add the new PHP Objects:

    /*
     * $data[0] => GameUserID
     * $data[1] => SlotID (In Game, INT)
     * $data[2] => GameUserName
     * $this => I've made a function called log($str) in the Main class, so I can
     * class this Function in the Player Class later
    */
    $this->log("Creating new player on SlotID #".$data[1]);
    $tmp = new Player($data[0], $data[2], $this);
    $this->players[$data[1]] = &$tmp;
    unset($tmp);

    //$this->players[$data[1]] = new Player($data[0], $data[2], $this);

The Class "Player" does not return anything on __construct().

I can't find the fail I make.

==============

I found out that the variable isn't saving after the function was called (reached the end). It's empty again whenever I call the function again.

  • 写回答

2条回答 默认 最新

  • dsd30433 2014-07-21 12:04
    关注

    You are passing an object to an array but then you're calling unset() on a variable that points to the object. Note that both variables point to the same object (even if you left out the & operator), so remove your call to unset().

    If you prefer, you can also immediately assign the object to your array:

     $this->players[$data[1]] = new Player($data[0], $data[2], $this);
    

    This way, you don't have a $tmp variable in the way. The code isn't harder to understand, in my opinion – on the contrary, $tmp doesn't really express much.


    Furthermore, I'm not sure where $data[1] is coming from or what it holds. If you are still having problems, please output all errors during development by putting error_reporting(E_ALL) at the top of your file. This can offer some very valuable insight as to what is going wrong.

    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能