<分区>
我是 PHP 新手。以下错误(?)花了我 891723498 个小时才在我的代码中找到。有人可以向我解释是什么原因造成的,也许还有解决方法吗?现在我只是离开 json_encode()
调用。
这是我的代码的精简版。除了 json_encode()
之外,可能还有其他函数具有相同的效果,我不知道。
这是我的 repl 的直接复制粘贴(使用 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>
这是来自 php -a
repl 的相同内容,但输出的帮助较小。
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 >
为什么 json_encode($datetime)
会“实现”$datetime 对象?
我最好的猜测是:
- 当在
json_encode()
中使用$datetime
对象时会发生某种活跃情况,而在访问属性时不会发生这种情况,
或
- 我在并行化的内部代码中遇到了某种竞争条件?