Static array variable of another class' objects does not allow calling methods of the second class [duplicate]
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.
So... what's up?
Try
self::$arData[$i]->show();
How about this:
foreach (self::$arData as $person) {
$person->show();
}
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.
精彩评论