There is a certain class "Task" which is filled with data. The setDate method is passed either null or a temporary string, the string is converted to an object of type \ DateTime ()

How to make it so that when getting a date via the getDate () method, the system would not break if the date property contains Null

Purpose: to reduce the number of conditions

How to solve a problem?

  1. Fill up the date of the FISH date - but in php this is how strangely it works. November is the default month
  2. To overload the DateTime class in DateTimeNull and return null to the method - but this solution violates the LSP and most likely will cause a lot of problems in the future
  3. Make an adapter over the DateTime and return the date of the 0000-00-00, or null or something else.
  4. Don't do anything, always check that the getDate () method contains
  5. Your option

class Task { private $date; /** * * @param $dateTime null | \DateTime */ function setDate($dateTime) { $this->date = \DateTime::createFromFormat('D d MYH:i:s +T', $dateTime); } /** * @param $dateTime * @return null|DateTime */ function getDate($dateTime) { return $this->date; } } /* -------как сейчас ------- */ $tasks = new Tasks(); foreach ($tasks as $task) { if (!$task->getDate()) { continue; } $task->getDate()->format('D'); } /* ------как надо-------- */ $tasks = new Tasks(); foreach ($tasks as $task) { $task->getDate()->format('D'); } 
  • ! $task->getDate() ? $task->getDate('now')->format('D') : $task->getDate()->format('D') ; - doox911

0