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;
}
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.
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With