如何使用foreach循环调用数组中对象的对象方法

时间:2012-04-25 19:58:16

标签: php oop foreach

我正在尝试存储一组对象,并且无法在foreach循环中调用对象方法。这基本上就是我所拥有的。打印功能不打印任何内容。我有什么东西在看,或者这不是解决问题的方法吗?

class person
{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function get_name() {
        return $this->name;
    }
}

$test_set[] = new person("John");
$test_set[] = new person("Jane");

foreach($test_set as $set_item) {
    print $set_item->get_name();
}

2 个答案:

答案 0 :(得分:4)

你需要像这样设置你的名字(可能只是一个错字):

public function __construct($name) {
    $this->name = $name; // not $this->$name
}

答案 1 :(得分:2)

你的循环正在运作。但是你的班级有一个错误。

替换:

    public function __construct($name) {
        $this->$name = $name;
    }

使用:

    public function __construct($name) {
        $this->name = $name;
    }