PHP Nullable types and function parameters

Viewed 109

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!

1 Answers

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.

Related