【问题标题】:Why are my PHP class methods "not compatible with Iterator" in Visual Studio Code anymore?为什么我的 PHP 类方法在 Visual Studio Code 中“与迭代器不兼容”了?
【发布时间】:2022-07-11 15:06:33
【问题描述】:

当我尝试在 PHP 中实现迭代器时,我很困惑为什么在 Visual Studio Code 中会遇到这些“问题”。之前没看到这些问题信息,不知道最近Iterator类是不是变了?还是有什么问题?

请参阅下面的屏幕截图以及 Visual Studio Code 中的错误消息。

下面是纯文本代码:

<?php
class MyList implements Iterator {
    private $my_list = [];  // Array of items
    private $index = 0;

    // Implemented Iterator methods
    public function current() { return $this->my_list[$this->index]; }
    public function key()     { return $this->index; }
    public function next()    { $this->index++; }
    public function rewind()  { $this->index = 0; }
    public function valid()   { return $this->index < count($this->my_list); }
}
?>

【问题讨论】:

  • 您是否尝试过添加返回类型:public function next(): void
  • @berend 谢谢!那解决了它...不知道有必要这样做:)
  • @berend 你应该让你的评论成为被接受的实际答案,人们可​​以实际看到解决方案,而无需阅读 cmets。

标签: php visual-studio-code


【解决方案1】:

问题

Intelephense 已检测到您的方法,例如MyList::next() 与方法 Iterator::next() 不兼容。

解决方案

返回类型添加到您的方法中:

class MyList implements Iterator {
    private $my_list = [];  // Array of items
    private $index = 0;

    // Implemented Iterator methods
    public function current() { return $this->my_list[$this->index]; }
    public function key()     { return $this->index; }
    public function next(): void    { $this->index++; }
    public function rewind(): void  { $this->index = 0; }
    public function valid(): bool   { return $this->index < count($this->my_list); }
}

参考

迭代器接口的documentation

 interface Iterator extends Traversable {
/* Methods */
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 2019-02-25
    • 2013-03-29
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2023-03-04
    相关资源
    最近更新 更多