0

Итератор должен быть реализован анонимным классом.

<?php
namespace lesson2;

header('Content-Type: text/html; charset=utf-8');


class User{
private $name;
private $balance;

function __construct($name,$balance){
    $this->name = $name;
    $this->balance = $balance;
}

public function getName(){
    return $this->name;
}

public function getBalance(){
    return $this->balance;
}

public function __toString(){
    return "У пользователя ".$this->getName()." сейчас на счету ".$this->getBalance()."<br/>";
}

public function giveMoney($user, $amount){
    if($amount > $this->balance){
        return 'Недостаточно средств!'."<br/>";
    }
    else{
        $this->balance -= $amount;
        $user->balance += $amount;
        return "Пользователь ".$this->name." перечислил ".$amount." пользователю ".$user->name."<br/>";
    }

}

}

abstract class Product{
private $name;
private $price;
private $owner;
static private $products=array();

function __construct($name, $price, $owner){
    $this->name = $name;
    $this->price = $price;
    $this->owner = $owner;
}

public function setOwner(User $user){
    $this->owner = $user;
}

public static function registerProduct($product){
    if (in_array($product, self::$products, true)) {
        echo 'Введены одинаковые продукты '.'</br>';
    }
    else{
        array_push(self::$products,$product);
    }
}
}

class Processor extends Product{
private $frequency;
public function __construct($name, $price, $owner,$frequency)
{
    parent::__construct($name, $price, $owner);
    $this->frequency=$frequency;
}

}

class Ram extends Product{
private $type;
private $memory;
public function __construct($name, $price, $owner, $type, $memory)
{
    parent::__construct($name, $price, $owner);
    $this -> type = $type;
    $this -> memory = $memory;
}
}

1 ответ 1

2

Создаём и возвращаем анонимный класс реализующий дефолтный интерфейс итератора https://www.php.net/manual/ru/class.iterator.php, также не забываем передать ему в конструктор наш массив.

class Product
{
    /**
     * @var mixed[]
     */
    static private array $products = [
        'Хлеб',
        'Консервы',
        'Энергетический напиток',
        'Водка',
        'Колбаса'
    ];

    public static function makeIterator(): Iterator
    {
        return new class (self::$products) implements Iterator {
            private int $position = 0;
            private array $array;

            public function __construct(array $array)
            {
                $this->array = array_values($array);
            }

            public function rewind(): void
            {
                $this->position = 0;
            }

            public function current()
            {
                return $this->array[$this->position];
            }

            public function key(): int
            {
                return $this->position;
            }

            public function next(): void
            {
                ++$this->position;
            }

            public function valid(): bool
            {
                return isset($this->array[$this->position]);
            }
        };
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.