无法在实例化DateTime PhP对象后立即应用函数



我尝试使用DateTime::提取字符串日期的年份。

我不明白为什么下面的DateTime实例化会抛出错误:

$myDate = "2015-09-10";
$year_myDate = new DateTime($myDate)->format("Y");

知道这个是有效的:

$myDate = "2015-09-10";
$dateTime_myDate = new DateTime($myDate);
$year_myDate = $dateTime_myDate->format("Y");

对象不返回自身的实例吗?那么,为什么不能在实例化之后立即使用该类的方法呢?

你可以,你只需要将你的实例化翘曲到括号中,例如

<>前$ year_myDate = (新DateTime(替换美元)) ->格式("Y");↑ ↑之前

注意:

  • $year_myDate,不会保存DateTime的实例,只是一个字符串(从DateTime::format()返回)