Search code examples
phpphp-7

What does ":?" after a method means in PHP?


I just saw this in a Symfony 4 application, and I can't find nowhere what it means

  public function findOneBySomeField($value): ?Article
    {
        return $this->createQueryBuilder('a')
            ->andWhere('a.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }

I know that, now with PHP 7 you can define the expected type of the returned value with ":int $val", but here, what does the ? symbol means ?


Solution

  • This is a new feature as of PHP 7.1. See the explanation here

    Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

    This means the expected output of your function will be either an Instance of the class Article or it is NULL.