I'm new to PHP. The following bug(?) took me 891723498 hours to locate in my code. Can someone explain to me what is causing this, and maybe a way to fix it? Right now I'm just leaving the json_encode()
call in.
This is a distilled version of my code. There may be other functions than json_encode()
that have the same effect, I don't know.
This is a straight copy-paste from my repl (using the Boris php repl -- https://github.com/borisrepl/boris).
./bin/boris
[1] boris> function broken () {
[1] *> $timezone = new DateTimeZone("America/New_York");
[1] *> $datetime = new DateTime("now", $timezone);
[1] *> return date_parse($datetime->date);
[1] *> }
// NULL
[2] boris>
[2] *> function works () {
[2] *> $timezone = new DateTimeZone("America/New_York");
[2] *> $datetime = new DateTime("now", $timezone);
[2] *> json_encode($datetime);
[2] *> return date_parse($datetime->date);
[2] *> }
// NULL
[3] boris> broken();
PHP Notice: Undefined property: DateTime::$date in /home/sirrobert/Projects/sirrobert/archon/code/repl/boris/lib/Boris/EvalWorker.php(152) : eval()'d code on line 4
// array(
// 'year' => false,
// 'month' => false,
// 'day' => false,
// 'hour' => false,
// 'minute' => false,
// 'second' => false,
// 'fraction' => false,
// 'warning_count' => 0,
// 'warnings' => array(
//
// ),
// 'error_count' => 1,
// 'errors' => array(
// 0 => 'Empty string'
// ),
// 'is_localtime' => false
// )
[4] boris> works();
// array(
// 'year' => 2016,
// 'month' => 11,
// 'day' => 30,
// 'hour' => 16,
// 'minute' => 53,
// 'second' => 35,
// 'fraction' => 0.0,
// 'warning_count' => 0,
// 'warnings' => array(
//
// ),
// 'error_count' => 0,
// 'errors' => array(
//
// ),
// 'is_localtime' => false
// )
[5] boris>
Here's the same thing from the php -a
repl with less helpful output.
php > function broken () {
php { $timezone = new DateTimeZone("America/New_York");
php { $datetime = new DateTime("now", $timezone);
php { return date_parse($datetime->date);
php { }
php >
php > function works () {
php { $timezone = new DateTimeZone("America/New_York");
php { $datetime = new DateTime("now", $timezone);
php { json_encode($datetime);
php { return date_parse($datetime->date);
php { }
php >
php > broken()
php > ;
PHP Notice: Undefined property: DateTime::$date in php shell code on line 4
php > works();
php >
Why in the world does the json_encode($datetime)
"realize" the $datetime object?
My best guess is that either:
- Some kind of vivification is happening when the
$datetime
object is being used injson_encode()
that isn't when it's being accessed for properties,
or
- I'm hitting some kind of race condition in parallelized internals code?