2014-06-16 47 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; }