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
  • 58,060
  • 25
  • 98
  • 150
Francisc
  • 77,430
  • 63
  • 180
  • 276

3 Answers3

3

Try

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

How about this:

foreach (self::$arData as $person) {
    $person->show();
}
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
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
  • 82,642
  • 24
  • 155
  • 189