6

I want to ask if both are the same and if not, where's the difference between them:

/**
 * @param int|null $id Any id.
 */
public function testSomething(int $id = null) {}

and

/**
 * @param int|null $id Any id.
 */
public function testSomething(?int $id) {}

Thank you for your answer!

2

2 Answers 2

5

It's different. The first function declaration :

public function testSomething(int $id = null) {}

sets the default value to null, if you call the function without an argument.

The second definition :

public function testSomething(?int $id) {}

will accept a null value as the first argument, but does not set it to a default value if the argument is missing. So you always need to have an argument if you call the function in the second way.

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

Comments

2

It's different. The first declaration use implicit nullable :

public function testSomething(int $id = null) {} // Only default value set to null

Note that this type of declaration is deprecated since PHP 8.4

You should instead use explicitly nullable which can be written in two ways:

public function testSomething(?int $id = null) {} // With the '?' marker

or

public function testSomething(int|null $id = null) {} // With the '|null' union type

About those these two in PHP 8.4: Implicitly nullable parameter declarations deprecated:

Both type declarations are effectively equivalent, even at the Reflection API. The second example is more verbose, and only works on PHP 8.0 and later.

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.