PHP Nullable types and function parameters
Asked Answered
M

2

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!

Manor answered 23/9, 2020 at 8:54 Comment(2)
the only difference I can see is that you cannot invoke testSomething(?int $id) {} without arguments - will probably throw a fatal error, whereas you can invoke the first case testSomething(int $id = null) {} without arguments.Wrasse
Does this answer your question? What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?Aurelioaurelius
L
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.

Limbert answered 23/9, 2020 at 9:53 Comment(0)
B
0

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.

Baugh answered 10/7 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.