Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays - foreach brings ->Fatal error: Cannot use object of type

Tags:

php

So, I'm mad about this Arrays, 2nd day givin me pain in *....

I'm developing an OOP PHP script.

I'm getting an array:

Array ( [0] => Project Object ( [project_id] => 1 [title] => Some Name [date] => 2011-10-20 [place] => Some City [customer] => 1 [proj_budget] => [manager] => 1 [team] => 1 [currency] => 1 ) )

When I'm trying to do this:

<?php
    $project = new Project();
    $projects = $project->findAll();
    print_r($projects);
    foreach ($projects as $temptwo) {
      echo $temptwo['title'].", \n";
    }
?>

I'm getting this:

Fatal error: Cannot use object of type Project as array

Why in the world? what does it want from me?

like image 437
mrGott Avatar asked Dec 01 '22 01:12

mrGott


2 Answers

You access the items as arrays

echo $temptwo['title'].", \n";

You probably want to access their properties

echo $temptwo->title.", \n";
like image 75
KingCrunch Avatar answered Dec 05 '22 12:12

KingCrunch


That's because you are looping an array of objects, so each item in your array is an object you'll need to address as an object.

foreach($projects as $temptwo){
    echo $temptwo->title;
}
like image 22
ChrisR Avatar answered Dec 05 '22 12:12

ChrisR