代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何在PHP/Eclipse中对foreach循环中从数组中拉出的自定义对象获取intellisense?

  •  9
  • Edward Tanguay  · 技术社区  · 15 年前

    自定义对象 (播客)排成一排。

    foreach公司 循环遍历这个集合,我没有 代码完成 在包含从集合中拉出的对象的变量上(例如在C#/VisualStudio中)。

    alt text

    <?php
    
    $podcasts = new Podcasts();
    echo $podcasts->getListHtml();
    
    class Podcasts {
        private $collection = array();
    
        function __construct() {
            $this->collection[] = new Podcast('This is the first one');
            $this->collection[] = new Podcast('This is the second one');
            $this->collection[] = new Podcast('This is the third one');
        }
    
        public function getListHtml() {
            $r = '';
            if(count($this->collection) > 0) {
                $r .= '<ul>';
                foreach($this->collection as $podcast) {
                    $r .= '<li>' . $podcast->getTitle() . '</li>';
                }
                $r .= '</ul>';
            }       
            return $r;
        }
    }
    
    class Podcast {
    
        private $title;
    
        public function getTitle() { return $this->title; }
        public function setTitle($value) {  $this->title = $value;}
    
        function __construct($title) {
            $this->title = $title;
        }
    
    }
    
    ?>
    

    附录

    谢谢,Fanis,我更新了我的FOREACH模板以自动包含该行:

    if(count(${lines}) > 0) {
        foreach(${lines} as ${line}) {
            /* @var $$${var} ${Type} */
    
        }
    }
    

    alt text

    2 回复  |  直到 15 年前
        1
  •  19
  •   Fanis Hatzidakis    15 年前

    是,请尝试:

    foreach($this->collection as $podcast) {
        /* @var $podcast Podcast */
        $r .= '<li>' . $podcast->getTitle() . '</
    }
    

    我已经有一段时间没有使用Eclipse了,但我记得它也曾经在那里工作过。

        2
  •  0
  •   santiago arizti    7 年前

    我的解决方案要求PHP7或更高。其思想是使用匿名函数映射数组,并利用类型暗示。

      $podcasts = getPodcasts();
      $listItems = array_map(function (Podcast $podcast) {
          return "<li>" . $podcast->getTitle() . "</li>";
      }, $podcasts);
      $podcastsHtml = "<ul>\n" . implode("\n", $listItems) . "\n</ul>";
    

    在大多数情况下 foreach 可以转换为 array_map 函数式程序设计

    如果您使用Laravel(我确信其他框架也有集合),您甚至可以用数组过滤器和其他类似的函数链接这些数组映射:

    $html = "<ul>" . collect($podcasts)
      ->filter(function (Podcast $p) { return $p !== null; }) // filtering example
      ->map(function (Podcast $p) { return "<li>".$p->getTitle()."</li>"; }) // mapping
      ->implode("\n") . "</ul>";
    

    但你来了!表示数组迭代的原生类型。

    推荐文章