鍍金池/ 問(wèn)答/PHP/ 關(guān)于PHP 內(nèi)置時(shí)間類函數(shù)的一個(gè)小問(wèn)題

關(guān)于PHP 內(nèi)置時(shí)間類函數(shù)的一個(gè)小問(wèn)題

<?php

$date = new DateTime();

$date->setTimezone(new DateTimeZone('Asia/Shanghai')); // 設(shè)置時(shí)區(qū)

//$now = $date->timezone;  // notice
//var_dump($now);          // null

print_r($date);

$now = $date->timezone;

echo $now;

請(qǐng)問(wèn)大家 注釋的地方為啥報(bào)錯(cuò)了 print 之后就能正常輸出了~~~ 抱大腿......

回答
編輯回答
任她鬧

這應(yīng)該是一個(gè)變量污染的bug
我猜測(cè)timezone是私有屬性
所以有個(gè)get方法public DateTimeZone getTimezone ( void )
var_dumpprint_r之后timezonepublic屬性了

https://bugs.php.net/bug.php?...

2018年1月21日 00:19
編輯回答
遲月

順便說(shuō)下 轉(zhuǎn)成數(shù)組是可以獲取到的

Beside from using DateTime::format() you can access the property using reflection:

<?php

$dt = new DateTime();
$o = new ReflectionObject($dt);
$p = $o->getProperty('date');
$date = $p->getValue($dt));
This is slight faster than using format() because format() formats a timestring that has already been formatted. Especially if you do it many times in a loop.

However this is not a regular behaviour of PHP. A bugreport has already been filed as @Nile mentioned in the comments above.

https://stackoverflow.com/que...

2018年6月1日 02:23