douhuang75397 2014-06-16 05:56 采纳率: 0%
浏览 14
已采纳

升级遗留PHP代码 - 这些表达式是否相同?

I am currently tasked with upgrading a library of pre-PHP5 code to conform with modern runtimes.

The library contains several uses of the following pattern:

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

According to the PHP documentation, this is illegal as of PHP 5.2, and will throw an exception (http://php.net/manual/en/migration52.error-messages.php)

My question is, how do I change the syntax to maintain the same functionality, while conforming to PHP 5.2+ standards? Does it suffice if I simply remove the ampersand?

$foo = new foo();
foreach($foo as $ref) {
    // Do something with $ref
}
  • 写回答

2条回答 默认 最新

  • donglun4682 2014-06-16 06:12
    关注

    For iterating through an object and its properties and modifying the original object you can use the foreach() like this:

     // Iterate over the object $foo
     foreach ($foo as $key => $ref) {
    
       // Some operation
       $newRef = $ref;
    
       // Change the original object
       $foo->$key = $newRef;
       }
    

    This will allow you to iterate only over the visible properties (as normally desirable). However, since you are migrating code into OOP, it might be desirable to just put the abstraction at a different level. The code above is good for arrays, but in OOP this is much more normal. Again, it depends on the case:

    // Create the object
    $foo = new foo();
    
    // Delegate the iteration to the inner method
    $foo->performAction();
    

    This makes the code calling the performAction() NOT to need to know about the properties of foo(), letting the object to handle its properties. Why would the house need to know about the door's knob? That's the door responsability.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan