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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?