5

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!

FryingPan
  • 81
  • 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. – jibsteroos Sep 23 '20 at 12:33
  • Does this answer your question? [What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?](https://stackoverflow.com/questions/48450739/what-is-the-purpose-of-the-question-marks-before-type-declaration-in-php7-stri) – Nico Haase Aug 19 '21 at 13:14
  • @FryingPan you can mark the answer bellow as correct – Aslanex Jun 22 '23 at 11:51

1 Answers1

4

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.

robsch
  • 9,358
  • 9
  • 63
  • 104
Inazo
  • 488
  • 4
  • 15