2

I am can't figure out why this doesn't work:

class Test
{
    public static $arData=array();

    public static function addMember(Person $member)
    {
        self::$arData[]=$member;
    }
    public static function showAll()
    {
        for($i=0;$i<count(self::$arData);$i++)
        {
            self::$arData[i]->show();
        }
    }
}

What I get is this: Fatal error: Call to a member function show() on a non-object. The show() method does exist and it basically prints out name and location of a person.
In in the constructor, instead of adding $member to $arData I do $member->show() it works.

So... what's up?

tereško
  • 57,247
  • 24
  • 95
  • 149
Francisc
  • 72,090
  • 61
  • 175
  • 271

3 Answers3

3

Try

self::$arData[$i]->show();
christopher_b
  • 938
  • 5
  • 13
2

How about this:

foreach (self::$arData as $person) {
    $person->show();
}
Alex Howansky
  • 47,154
  • 8
  • 74
  • 95
1

The error is in the for-loop:

...
public static function showAll()
{
    for($i=0;$i<count(self::$arData);$i++)
    {
        self::$arData[$i]->show();
    }
}
...

It must be $i and not only i in the array-access-operator when calling the show()-method.

Stefan Gehrig
  • 80,936
  • 24
  • 154
  • 184