开发者

Static array variable of another class' objects does not allow calling methods of the second class [duplicate]

This question already has answers here: Call to a member function on a non-object [duplicate] (8 answer开发者_如何学编程s) Closed 10 years ago.

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜