Why are my PHP class methods "not compatible with Iterator" in Visual Studio Code anymore?

Viewed 357

I am confused why I get these "problems" in Visual Studio Code when I try to implement an Iterator in PHP. I have not seen these problem messages earlier, so I wonder if the Iterator class has been changed lately? Or is anything else wrong?

See screenshot below with error message in Visual Studio Code.

enter image description here

Here's the code in plain text as well:

<?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); }
}
?>
1 Answers

Problem

Intelephense has detected your method, e.g. MyList::next() is not compatible with method Iterator::next().

Solution

Add the return type to your methods:

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

    // Implemented Iterator methods
    public function current(): mixed { return $this->my_list[$this->index]; }
    public function key(): mixed     { 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); }
}

Reference

The documentation for the Iterator interface:

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