2014-06-16 50 views
0

我目前的任務是升級一個PHP5之前的代碼庫以符合現代運行時。升級舊版PHP代碼 - 這些表達式是否相同?

庫中包含以下模式的幾個用途:

$foo = new foo(); 
foreach($foo as &$ref) { 
    // Do something with $ref 
} 

根據PHP文檔,這是PHP 5.2的非法的,將拋出一個異常(http://php.net/manual/en/migration52.error-messages.php

我的問題是,如何修改語法以保持相同的功能,同時符合PHP 5.2+標準?如果我簡單地刪除&符號就足夠了嗎?

$foo = new foo(); 
foreach($foo as $ref) { 
    // Do something with $ref 
} 
+0

'$ foo'數組中保存了哪些類型的元素? – Mantas

+0

任何可能被迭代的對象(http://php.net/manual/en/language.oop5.iterations.php)。 – csvan

+0

[Using foreach with SplFixedArray](http://stackoverflow.com/questions/22942860/using-foreach-with-splfixedarray) –

回答

2

對於iterating through an object and its properties和修改原始對象,你可以使用foreach()這樣的:

// Iterate over the object $foo 
foreach ($foo as $key => $ref) { 

    // Some operation 
    $newRef = $ref; 

    // Change the original object 
    $foo->$key = $newRef; 
    } 

這將允許你只在可見性循環(如通常所期望的)。但是,由於您正在將代碼遷移到OOP中,因此可能需要將抽象級別置於不同的級別。上面的代碼對數組很有用,但是在OOP中這更加正常。再次,它取決於案件:

// Create the object 
$foo = new foo(); 

// Delegate the iteration to the inner method 
$foo->performAction(); 

這使得代碼調用performAction()不要將需要了解的foo()屬性,讓對象來處理其屬性。爲什麼房子需要知道門的旋鈕?這是門的責任。

-1

如果$foo只包含數組或標量值。做

foreach($foo as $key => $ref) { // Do something with $ref $foo->{$key} = $ref; }