0

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.

1 Answer 1

1

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;
}

Ref: PHP > New Features > Nullable types

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.