DateTime as an optional parameter (default is "now", not null)?

Is it possible to set a DateTime object as an optional parameter using now by default?

The following code gives me a syntax error :

 public function getData(array $metrics, DateTime $start, DateTime $end = new DateTime, $params = array()) { // Default DateTime constructor automatically use "now" } 

It's just a matter of curiosity, I know what I can do :

 public function getData(array $metrics, DateTime $start, DateTime $end = null, $params = array()) { $end = is_null($end) ? new DateTime() : null; } 
+6
source share
1 answer

No, you cannot set an object as the default function / method parameter. From the doc:

Default Argument Values
A function can define C ++-style defaults for scalar arguments ...

An object is not a scalar data type .

+6
source

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


All Articles