yaleksandr89
@yaleksandr89
PHP developer

Реализация класса interval. Как описать метод __toString()?

Здравствуйте.
Решаю задачку и одно из условий поставило меня в ступор. Сама задача.

класс Date

<?php declare(strict_types=1);

namespace PracticalTasks;

class Date
{
    private $date;

    public function __construct($date = null)
    {
        if ($date) {
            $this->date = $date;
        } else {
            $this->date = date('Y-m-d');
        }
    }

    public function getDay(): string
    {
        return date('d', strtotime($this->date));
    }

    public function getMonth($lang = null): string
    {
        if ($lang) {
            if ($lang === 'ru') {
                $monthsList = [
                    '01' => 'Январь',
                    '02' => 'Февраль',
                    '03' => 'Март',
                    '04' => 'Апрель',
                    '05' => 'Май',
                    '06' => 'Июнь',
                    '07' => 'Июль',
                    '08' => 'Август',
                    '09' => 'Сентябрь',
                    '10' => 'Октябрь',
                    '11' => 'Ноябрь',
                    '12' => 'Декабрь'
                ];
                $month = date('m', strtotime($this->date));
                return str_replace($month, $monthsList[$month], $month);
            }
            if ($lang === 'en') {
                return date('F', strtotime($this->date));
            }
        }
        return date('m', strtotime($this->date));
    }

    public function getWeekDay($lang = null)
    {
        if ($lang) {
            if ($lang === 'ru') {
                $monthsList = [
                    1 => 'Понедельник',
                    2 => 'Вторник',
                    3 => 'Среда',
                    4 => 'Четверг',
                    5 => 'Пятница',
                    6 => 'Суббота',
                    7 => 'Воскресенье',
                ];
                $weekDay = date('N', strtotime($this->date));
                return str_replace($weekDay, $monthsList[$weekDay], $weekDay);
            }
            if ($lang === 'en') {
                return date('l', strtotime($this->date));
            }
        }
        return date('N', strtotime($this->date));
    }

    public function getYear(): string
    {
        return date('Y', strtotime($this->date));
    }

    public function addDay(int $quantityDay): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "+$quantityDay day"));
        return $this;
    }

    public function subDay(int $quantityDay): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "-$quantityDay day"));
        return $this;
    }

    public function addMonth(int $quantityMonth): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "+$quantityMonth month"));
        return $this;
    }

    public function subMonth(int $quantityMonth): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "-$quantityMonth month"));
        return $this;
    }

    public function addYear(int $quantityYear): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "+$quantityYear year"));
        return $this;
    }

    public function subYear(int $quantityYear): self
    {
        $this->date = date('Y-m-d', strtotime($this->date . "+$quantityYear year"));
        return $this;
    }

    public function customFormat(string $format)
    {
        return date($format, strtotime($this->date));
    }

    public function __toString()
    {
        return (string)$this->date;
    }
}


класс Interval

<?php declare(strict_types=1);

namespace PracticalTasks;

require_once 'Date.php';

class Interval
{
    private Date $startDate;
    private Date $endDate;

    public function __construct(Date $startDate, Date $endDate)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
    }

    public function toDays(): string
    {
        $diff = $this->endDate->getDay() - $this->startDate->getDay();
        return 'Разница (в днях) между датами = ' . abs($diff) . '.';
    }

    public function toMonths(): string
    {
        $diff = $this->endDate->getMonth() - $this->startDate->getMonth();
        return 'Разница (в месяцах) между датами = ' . abs($diff) . '.';
    }

    public function toYears(): string
    {
        $diff = $this->endDate->getYear() - $this->startDate->getYear();
        return 'Разница (в годах) между датами = ' . abs($diff) . '.';
    }

    public function __toString()
    {
        // ...
    }
}



Загвоздка возникла в последнем пункте:
public function __toString()
    {
        // выведет результат в виде массива
        // ['years' => '', 'months' => '', 'days' => '']
    }


Насколько мне известно метод __toString(), срабатывает когда мы пытаемся преобразовать объект в строку и возвращать он должен строку. Соответственно не могу понять, как вывести по средствам этого метода массив (и возможно ли это). Или я неправильно понял данное условие.

Уже просто самому интересно :)

P.S. про стандартный класс DateTime знаю :), реализовал через date() так как это было в условии.
  • Вопрос задан
  • 171 просмотр
Решения вопроса 1
DevMan
@DevMan
никак: __toString возвращает строку.
и var_dump в примере не имеет никакого отношения к __toString

кстати, у вас логическая ошибка в коде.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы