Bug #80047 [Opn->Csd]: DatePeriod doesn't support custom DateTimeImmutable

From: Date: Fri, 24 Jun 2022 10:22:21 +0000
Subject: Bug #80047 [Opn->Csd]: DatePeriod doesn't support custom DateTimeImmutable
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-241801@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=80047&edit=1 ID: 80047 Updated by: derick@php.net Reported by: oognic at gmail dot com Summary: DatePeriod doesn't support custom DateTimeImmutable -Status: Open +Status: Closed Type: Bug Package: Date/time related PHP Version: 7.2.33 -Assigned To: +Assigned To: derick Block user comment: N Private report: N New Comment: The fix for this bug has been committed. If you are still experiencing this bug, try to check out latest source from https://github.com/php/php-src and re-test. Thank you for the report, and for helping us make PHP better. The fix that I have committed is to *now* allow inherited objects here. The DatePeriod iterator needs to construct DateTime/DateTimeImmutable objects which can only done by copying internal data, which can't be recreated by calling the constructor of an inherited class. This data needs to be directly injected into a (new) DateTime/DateTimeImmutable object. Previous Comments: ------------------------------------------------------------------------ [2020-09-03 12:01:06] oognic at gmail dot com Description: ------------ If we create a custom class that inherits from DateTimeImmutable, this class can be given as parameter to DatePeriod. However, when iterating or trying to get the start or end dates, DatePeriod will try to return instances of our custom class but without using its constructor, which will produce incoherent objects. See this PR for more details: https://github.com/thecodingmachine/safe/pull/227/files Test script: --------------- <?php class CustomDateTimeImmutable extends \DateTimeImmutable { private $foo; public function __construct($time = "now", $timezone = NULL) { parent::__construct($time, $timezone); $this->foo = "foo"; } public function getFoo() { return $this->foo; } } $datePeriod = new \DatePeriod(new CustomDateTimeImmutable('2020-01-01'), new \DateInterval('P1D'), (new CustomDateTimeImmutable('2020-01-03'))->modify('+1 day')); var_dump($datePeriod->getStartDate()->getFoo()); $strings = []; foreach ($datePeriod as $date) { var_dump($date->getFoo()); } Expected result: ---------------- "foo" "foo" "foo" "foo" Actual result: -------------- NULL NULL NULL NULL ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=80047&edit=1

« previous php.bugs (#241801) next »