|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2019-12-28 11:58 UTC] robert at korulczyk dot pl
Description: ------------ In PHP 7.4 behavior of `foreach (new DateTime() as $property => $value)` has changed. Prior to 7.4 foreach iterates through virtual properties of DateTime object. Since 7.4 it is treated as empty array, which makes it incosistent with `json_encode()` and `(array)` cast. Cast to array was already fixed in https://bugs.php.net/bug.php?id=78383 https://3v4l.org/h99LLn Context - foreach approach is used in Json helper in Yii 2: https://github.com/yiisoft/yii2/issues/17760 https://github.com/yiisoft/yii2/blob/a636ff916ac3a06756f37c0dbfb55994394a6a55/framework/helpers/BaseJson.php#L160-L166 Test script: --------------- $date = new DateTime('2019-12-24'); $properties = []; foreach ($date as $k => $v) { $properties[$k] = $v; } var_dump($date); var_dump((array) $date); var_dump($properties); echo json_encode($date), "\n"; echo json_encode((array) $date), "\n"; echo json_encode($properties), "\n"; Expected result: ---------------- object(DateTime)#1 (3) { ["date"]=> string(26) "2019-12-24 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } array(3) { ["date"]=> string(26) "2019-12-24 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } array(3) { ["date"]=> string(26) "2019-12-24 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } {"date":"2019-12-24 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Amsterdam"} {"date":"2019-12-24 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Amsterdam"} {"date":"2019-12-24 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Amsterdam"} Actual result: -------------- object(DateTime)#1 (3) { ["date"]=> string(26) "2019-12-24 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } array(3) { ["date"]=> string(26) "2019-12-24 00:00:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "Europe/Amsterdam" } array(0) { } {"date":"2019-12-24 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Amsterdam"} {"date":"2019-12-24 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Amsterdam"} [] PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 08:00:01 2025 UTC |
Also there is a problem with reflection. Reflection is not returning the datetime properties. So $props array will remain empty.. $date = new DateTime(); $reflection = new ReflectionObject($date); $props = []; foreach ($reflection->getProperties() as $p) { $props[] = $p->getName(); } var_dump($props);