Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is possible to set a DateTime object as optional parameter using now as 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 i can do:

public function getData(array $metrics, DateTime $start,
    DateTime $end = null, $params = array())
{
    $end = is_null($end) ? new DateTime() : null;
}
like image 333
gremo Avatar asked Jan 14 '12 13:01

gremo


People also ask

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

What is the default value for DateTime?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).

What are default and optional parameters?

By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition.

Is it mandatory to specify a default value to optional parameter?

Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression. Every parameter following an optional parameter in the procedure definition must also be optional.


Video Answer


1 Answers

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

Default argument values
A function may define C++-style default values for scalar arguments ...

An object is not a scalar datatype.

like image 50
Tim Cooper Avatar answered Oct 23 '22 16:10

Tim Cooper