dragon7088 2017-02-13 09:32
浏览 222

如何在php中创建对象列表

I am .net developer just started to work on PHP project with Laravel framework. In .net, we can create List frequently. What is the alternate way of doing same in PHP. After that, I want to pass that list as method parameter & accessing list items. I searched on google but can't find anything suitable. I know this may be very basic question from the view point of PHP developers. But I am still in confusion & can not proceed with my work.

eg in .net code, we create list object as -

public List<ReaderInfo> readerInfo = null;

To pass that list object in method -

InitReaderInfo(readerInfo);

Method definition is written as -

public void InitReaderInfo(List<ReaderInfo> reader)

Now, I want to convert the same in PHP. Any suggestion?

  • 写回答

1条回答 默认 最新

  • doujie9882 2017-02-13 11:42
    关注

    PHP is not a strong type language. It also doesn't support generics or generic methods. That general means you cannot write this:

    public List<ReaderInfo> readerInfo = null;
    

    or this:

    public void InitReaderInfo(List<ReaderInfo> reader)
    

    There is no easy way to enforce type to list elements just by defining it. However, PHP supports argument types declaration so you can do this:

    <?php
    
    class Thing {
      private $name;
      public function __construct($name) {
        $this->name = $name;
      }
      public function __toString() {
        return $this->name;
      }
    }
    
    class Fruit extends Thing {}
    
    class ThingList {
      private $list;
      public function __construct(Thing ...$list) {
        $this->list = $list;
      }
      public function __toString() {
        return array_reduce($this->list, function ($carry, $item) {
          return $carry . $item . "
    ";
        }, '');
      }
    }
    
    function PrintThings(ThingList $list) {
      // ... do something to the thing list
      echo $list;
    }
    
    ?>
    

    in order to get better type-safety like this:

    <?php
    
    // declare a list of thing
    $things = new ThingList(
      new Thing("apple"),
      new Fruit("orange")
    );
    
    PrintThings($things);
    
    ?>
    

    If you're talking about Laravel specific solution, I suggest you to look at the jcrowe/type-safe-collection library, which you can do similar thing with a lot less labour.

    评论

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据