0

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)

1
  • check your syntax. $this->id not $this->$id, echo $picObj->fileName; not echo $picObj->$fileName; Commented Nov 4, 2015 at 7:47

3 Answers 3

2

You have to access the object attributes without the dollar sign, example:

foreach($pics as $picObj) {
   echo $picObj->fileName;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's working now. Also I had to remove the dollar signs in my class e.g. $this->id not $this->$id as mentioned by the user Phpstall.
0

try array_push($pics, $newObj); instead of $pics[] = $newObj;

edit:

can you post your extract(value) method?

Comments

0

In the constructor class, you made a mistake

$this->$id = $id is wrong

$this->id = $id is correct

same for all other variables

1 Comment

This fixed it in combination with also accessing the object attributes without $.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.