FryingPan
FryingPan

Reputation: 113

PHP Nullable types and function parameters

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!

Upvotes: 6

Views: 1835

Answers (2)

Sunchock
Sunchock

Reputation: 388

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.

Upvotes: 1

Inazo
Inazo

Reputation: 498

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.

Upvotes: 5

Related Questions