Trying to iterate array of objects PHP

Tuesday, November 3, 2015

I have a method in which I want to parse input from an SQL-Row into an object:



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;
}


My PICObject looks like this:



  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;
}
}


Now ideally I want to iterate this $pics array which should now contain several PICObjects and be able to access its fields:



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


However, this doesn't work. So how to do this? (I've tried it several ways but nothing really did what I was looking for)

0 comments:

Post a Comment