dongzha2525 2015-12-19 00:52
浏览 132
已采纳

PHP - 无法将对象添加到数组中

I've created a simple class:

class Event {


   var $a;
   var $b;
   var $c;


   function __construct($a, $b, $c) 
   {
      $this->a= $a;
      $this->b = $b;
      $this->c= $c;
   }



  } 

Then I've created another class which extends Thread:

class WorkerThread extends Thread
{
    private $myUrl;
    private $eventsArr;
    private $counterDebug;
    private $postdata;

    public function __construct($myUrl, $postdata)
    {
        $this->myUrl = $myUrl;
        $this->postdata = $postdata;
        $this->eventsArr = array();
        $this->counterDebug=0;
    }

    public function run()
    {
          $flag=false;

          foreach ($json as $key => $value) {


                    $this->counterDebug++;
                    /* Death event */
                    $event= new Event($a, $b, $c);
                    array_push($this->eventsArr, $event);

                }
              }

            }
          }
          echo (count($this->eventsArr));
          echo (json_encode($event));
          echo ("
" . $this->counterDebug);

    if($flag && count($this->events)>0){
    ...

When trying to add new created objects into the array, it stays empty.

What I've figured from debugging:

1) The objects are created.

2) neither eventsArr[]= $event, nor array_push are working.

3) I've set a counter that verifies the objects are being created and should be added to the array.

What am I doing wrong?

p.s-

I've removed irrelevant parts of code in order to simplify things.

  • 写回答

1条回答 默认 最新

  • doufei1893 2015-12-19 01:02
    关注

    i think you should create temp array which have all your events and then give it to $eventsArr like this.

    $temp = array();
    foreach ($json as $key => $value) {
        $this->counterDebug++;
        /* Death event */
        $event= new Event($a, $b, $c);
        $temp[] = $event;
    }
    $this->eventsArr = $temp;
    

    OR

    foreach ($json as $key => $value) {
        $this->counterDebug++;
        /* Death event */
        $event= new Event($a, $b, $c);
        $this->eventsArr[] = $event;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大