I wanted to know if the new feature of nullable types can be used to change the syntax in this working function from
function getCustomerId($id = null)
{
return $id ?: 2;
}
echo getCustomerId();
to something like this which isn't working for me. I get the error for too few arguments.
function getCustomerId(?int $id)
{
return $id ?: 2;
}
echo getCustomerId();
so that basically if the argument is not provided it returns 2, but if the argument is provided it returns that argument.
Yer kinda confusing the concept of optional arguments with the concept of nullable ones.
An optional arguments means you don't need to pass it cos it's optional.
A nullable argument means that whilst the argument needs to be of a certain type, that null
is also valid (where it wouldn't be if it wasn't nullable). Nullability doesn't mean you don't need to pass anything; you still do. It can just be null
.
If you want to have an integer argument which is optional and considered null if not passed, then combine yer two examples:
function getCustomerId(?int $id=null)
{
return $id ?: 2;
}