在PHP中将DateTime连接到字符串变量时出错


Error when concatenating DateTime to a string variable in PHP

我试图创建一个包含当前服务器时间的字符串,但在执行串联操作时出错。

以下操作很好:

$date = new DateTime('now', new DateTimezone('Africa/Johannesburg'));
echo $date->format('Y-m-d H:i:s');
$message = 'There is a new event occurred ';
echo $message;

但当我试图将消息和格式化日期连接在一起时,我会得到一个HTTP500错误。

$date = new DateTime('now', new DateTimezone('Africa/Johannesburg'));
echo $date->format('Y-m-d H:i:s');
$message = 'There is a new event occurred at '.date->format('Y-m-d H:i:s');  
echo $message;

我有什么不明白的?

正如您所发现的,第二个例子应该是:

$message = 'There is a new event occurred at '. $date->format('Y-m-d H:i:s');  

根据你的陈述,你已经挣扎了两个小时,你可能只有一个空白屏幕或"内部服务器错误"类型的页面,没有给你任何细节。

调试这种问题:

1) 查找web服务器的错误日志(例如error_log)。你会在里面找到这样的东西:

[Thu Mar 31 19:28:24 2016] [error] [client 10.42.88.12] PHP Parse error:
syntax error, unexpected T_OBJECT_OPERATOR in /var/www/htdocs/datetest.php on line 9

2) 找到控制php安装的php.ini文件并设置值:

display_errors = On 

这将直接在您的web浏览器中显示相同的"分析错误:"。您应该而不是为生产服务器启用该设置,但这在开发过程中非常有用。