mrGott
mrGott

Reputation: 1076

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

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?

Upvotes: 4

Views: 12353

Answers (5)

user2908225
user2908225

Reputation: 79

You try to get the data of object. It seems as an array but it is not. it is an object so you have to use

$temptwo->title

Upvotes: 1

ChrisR
ChrisR

Reputation: 14447

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

Upvotes: 5

Jonnix
Jonnix

Reputation: 4187

Try using:

echo $temptwo->title.", \n";

instead.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798884

It wants you to use the object as an object, not an array.

    echo $temptwo->title . ", \n";

Upvotes: 2

KingCrunch
KingCrunch

Reputation: 131981

You access the items as arrays

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

You probably want to access their properties

echo $temptwo->title.", \n";

Upvotes: 9

Related Questions