Why does Passing Access modfiers to a method in PHP Return a Parse error (Iterator)

  iterator, php

I have been trying to pass various access modifiers (public, private, and protected) in my method (3rd line). Unfortunately, I get a Parse error when running the code. Please, see the code below:

class MappedIteratorDemo implements Iterator
{
    public function __construct(private array $items = []){}

    public function current()
    {
        // TODO: Implement current() method.
        return current($this->items);
    }

    public function next()
    {
        // TODO: Implement next() method.
        return next($this->items);
    }

    public function key()
    {
        // TODO: Implement key() method.
        return key($this->items);
    }

    public function valid()
    {
        // TODO: Implement valid() method.
        return key($this->items) !== null;
    }

    public function rewind()
    {
        // TODO: Implement rewind() method.
        return reset($this->items);
    }
}

$mappedArray = [
    'name'      => 'Ola',
    'location'  => 'Essen, Germany',
    'role'      => 'Software Developer',
];

$mappedIterDemo = new MappedIteratorDemo($mappedArray);
foreach ($mappedIterDemo as $item =>$value)
{
    print "$item : $value" . PHP_EOL;
}

And its corresponding error


PHP Parse error:  syntax error, unexpected 'private' (T_PRIVATE), expecting variable (T_
VARIABLE) in ...

My PHP version is PHP: 8.0 running on PHPStorm IDE.

I would appreciate any tips/guidance on possible solutions.

Thank you

Source: Ask PHP

LEAVE A COMMENT