2012-04-25 71 views
2

我想存儲對象的集合,並且無法在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(); 
} 
+1

我複製粘貼你的代碼,它工作正常。問題在別的地方。您是否打開了錯誤報告? – 2012-04-25 20:08:33

+0

這是我的代碼的簡化版本。我複製粘貼它,它也工作。它必須是我更高級的課程中的一些東西。 – wachpwnski 2012-04-25 20:14:41

+0

試試這個代碼。它可能是多參數結構? https://gist.github.com/a7e525e84cb95057a676 – wachpwnski 2012-04-25 20:23:43

回答

4

你需要設置你的名字是這樣的(可能只是一個錯字):

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

這是這裏的一個錯字。它仍然不會更改空白輸出。 – wachpwnski 2012-04-25 20:03:06

+0

對我來說,它可以在測試文件中工作。使用'error_reporting(E_ALL)'輸出任何錯誤; ini_set('display_errors','1');'在頂部? – 2012-04-25 20:08:28

+0

同意 - 它也適用於我。 – Kasapo 2012-04-25 20:10:30

2

你的循環工作。但是你的班級有一個錯誤。

替換:

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

有了:

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

不知道爲什麼你被低估了...... +1,因爲這是正確的。 – Kasapo 2012-04-25 20:09:01

+1

唉@匿名反對票。也許是因爲downvoter認爲它比幾乎類似的答案遲了幾分鐘。但仍然是正確的。 – 2012-04-25 20:09:52