Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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;
    }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!