试图迭代PHP对象数组

时间:2015-11-04 07:37:26

标签: php arrays loops object

我有一个方法,我想将SQL-Row的输入解析为一个对象:

function buildPictureArray($sqlRow) {
   $pics = [];
   foreach($sqlRow as $value) {
      extract($value); // How to do this more elegant?
      $newObj = new PICObject($id, $filename, $thumb . $filename, $full . $filename, $title, $subtitle); // These are column names I got from extract
      $pics[] = $newObj;
   }
   return $pics;
}

我的PICObject看起来像这样:

  Class PICObject {
    public $id;
    public $fileName;
    public $thumbLink;
    public $fullLink;
    public $title;
    public $subTitle;

    function __construct($id, $fileName, $thumbLink, $fullLink, $title, $subTitle) {
      $this->$id = $id;
      $this->$fileName = $fileName;
      $this->$thumbLink = $thumbLink;
      $this->$fullLink = $fullLink;
      $this->$title = $title;
      $this->$subTitle = $subTitle;
    }
  }

现在理想情况下我想迭代这个$ pics数组,它现在应该包含几个PICObject并能够访问它的字段:

foreach($pics as $picObj) {
   echo $picObj->$fileName;
}

然而,这不起作用。那怎么做? (我已经尝试了几种方法,但没有真正做到我想要的东西)

3 个答案:

答案 0 :(得分:2)

您必须在没有美元符号的情况下访问对象属性,例如:

foreach($pics as $picObj) {
   echo $picObj->fileName;
}

答案 1 :(得分:0)

尝试array_push($pics, $newObj);而不是$pics[] = $newObj;

编辑:

您可以发布extract(value)方法吗?

答案 2 :(得分:0)

在构造函数类中,你犯了一个错误

$ this-> $ id = $ id错误

$ this-> id = $ id是正确的

所有其他变量