1

Strange, but couldn't find this on SO, maybe someone can help.

What does this syntax mean in PHP when we have a colon followed by a question mark and then another class name when a method is being defined?

public function someMethod(): ?SomeClass

Full function just in case with oriignal names

    public function getParentProject(): ?ParentProjectTester
    {
        return $this->parentProject;
    }
Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58
Robert Sinclair
  • 4,550
  • 2
  • 44
  • 46
  • 1
    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) – Syscall Jan 30 '22 at 08:56

3 Answers3

2

This syntax means that the method is forced to return NULL (what the question mark stands for) or and instance of the declared class. Refer to: php docs.

If something else is returned, this will cause an error like: Return value of Name\Space::method() must be of the type ..., ... returned in /Path/To/File.php on line ....

It's good practice to use this strict typing in object oriented programming so the code is more unambiguous and less sensitive to errors.

But it's not obligated to use, your code will work perfectly fine if you remove the return type and just use public function getParentProject().

Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58
  • 1
    ty! i assumed it was a ternary operator of some kind but wasn't 100% sure what it does. Think it's a php 7+ thing. Thanks for the clarifications! – Robert Sinclair Jul 23 '21 at 13:57
1

That is a return type declaration, telling you the type it should return: https://www.brainbell.com/php/type-declarations-hints.html#return-type

The question mark means it's nullable, meaning it might be null and not that type.

greendemiurge
  • 509
  • 3
  • 11
1

The question mark indicates that the function may return in instance of that class, or it may return null. It's called a nullable type and you can read about it here.

Simon Brahan
  • 2,016
  • 1
  • 14
  • 22