2011-05-20 68 views
1

爲什麼,如果我有對象的數組是這樣的:PHP的foreach對對象的數組

class testClass { 

    private $_x = 10; 

    public function setX($x) { 
     $this->_x = $x; 
    } 

    public function writeX() { 
     echo $this->_x . '<br />'; 
    } 

} 

$t = array(); 

for ($i = 0; $i < 10; $i++) { 
    $t[] = new testClass(); 
} 

print_r($t); 

我可以的foreach這樣的循環:

foreach ($t as $tt) { 
    $tt->y = 7; 
    $tt->setX($counter); 
    $counter+=100; 
} 

print_r($t); 

或者這樣:

foreach ($t as &$tt) { 
    $tt->y = 7; 
    $tt->setX($counter); 
    $counter+=100; 
} 

print_r($t); 

和結果會是平等的嗎?但是,如果我有數組中的標量值,它們只能通過($ arr作爲& $ v),僅通過引用$ v進行修改?

回答

3

這取決於您使用的是PHP5還是早期版本。

在PHP5中,同樣的事情,因爲它是一個對象數組。 (其他類型不一樣)。

在PHP4中,不是一回事。 (但是,然後再次,第二個會抱怨語法無論如何。)

+0

所以我必須記住這種行爲「原樣」? – 2011-05-20 13:14:23

+0

或者,您可能需要閱讀以下內容:http://www.php.net/manual/en/language.oop5.references.php – 2011-05-20 13:24:48

+0

哪裏可以在本手冊中找到有關我的問題的信息? – 2011-05-20 13:41:30