我有一个DateTime对象的数组,需要在函数调用中使用它们作为字符串。我尝试像这样进行转换:$string_datetime = (string)$myDateTimeObject;但是它不起作用。搜索也没有结果,因为大多数人都在问如何将字符串转换为DateTime,而不是相反。
我的代码:
我的代码:
$start_date = new DateTime();
$end_date = new DateTime();
$end_date = $end_date->modify('+1 day');
// Add time range to request
$request['time_range'] = Array ( 'start' => $start_date,
'end' => $end_date);
在调用一个期望字符串的函数(它是一个API调用)时,我收到了这个错误:
可捕获的致命错误:无法将DateTime类的对象转换为字符串
从DateTime对象中转换/提取字符串的正确方法是什么?
DateTime
不能被隐式转换为字符串有些疏忽了。个人而言,我使用一个扩展它并添加__toString()
方法(使用DateTime:: format()
)的包装类。在我看来,仍应该是本地功能。 - FtDRbwLXw6__toString()
进行扩展是开发人员明智的决定,它允许您根据自己的需求DRY实现。我的意思是,当随意调用__toString()
时,您期望发生什么? - Anther