我是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对象?
我最好的猜测是:
$datetime
对象在json_encode()
中使用而不是在为属性访问时,会发生某种形式的活动,或
答案 0 :(得分:0)
好的,根据提供的评论和链接,根据http://bugs.php.net/bug.php?id=49382和Why can't I access DateTime->date in PHP's DateTime class? Is it a bug?
,这似乎是一个已知(但没有优先级)的问题问题似乎是延迟加载DateTime类,通过直接访问对象的属性显然没有正确触发。
解决方案显然是做我做的(无操作)或做特定的字符串格式化,即使你想要的格式是默认的->date
格式。