10

我在数组中有一组自定义对象(Podcast)。

当我使用foreach循环遍历此集合时,我没有对包含从集合中拉出的对象的变量进行代码完成(例如在 C#/VisualStudio 中)。

有没有办法给 PHP 一个类型提示,以便 Eclipse 知道从集合中拉出的对象的类型,以便它可以在智能感知中向我显示该对象的方法?

替代文字

<?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} */

    }
}

替代文字

4

2 回答 2

19

是的,试试:

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

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

于 2010-09-18T15:49:12.423 回答
0

这可能会帮助互联网上的其他一些人寻找更简洁的解决方案来解决这个问题。

我的解决方案需要 PHP7 或更高版本。这个想法是用匿名函数映射数组并利用类型提示。

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

在大多数情况下,aforeach可以转换为 a array_map,只需将范式转换为函数式编程

如果你使用 Laravel(我相信其他框架也有 Collections),你甚至可以将这些数组映射与数组过滤器和其他类似这样的功能性东西链接起来:

$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>";

在普通的 php 中链接这些数组函数看起来很丑陋......

但是你去吧!一种提示数组迭代的本机类型。

于 2018-08-07T22:16:24.083 回答