Unable to apply function immediately after initializing DateTime PhP object

I am trying to extract the year of a string date using DateTime::.

I do not understand why the following DateTime creation causes an error:

$myDate = "2015-09-10";

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

knowing that this really works:

$myDate = "2015-09-10";

$dateTime_myDate = new DateTime($myDate);

$year_myDate = $dateTime_myDate->format("Y");

Will the object return an instance of itself? So, why can't we use the method of this class right after instantiation?

+4
source share
1 answer

You can, you just have to deform your instantiation into parentheses, for example.

$ year_myDate = ( new DateTime ($ myDate) ) -> format ("Y");
               ↑ ↑

Note:

  • PHP >= 5.4
  • $year_myDate, DateTime, ( DateTime::format())
+3

Source: https://habr.com/ru/post/1606740/


All Articles