Skip to content
Advertisement

Method followed by colon and a question mark and a class

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;
    }

Advertisement

Answer

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 NameSpace::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().

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement