Since php7 we already know that it is possible to declare the function's return type. Then if that function returns something else, an exception is thrown.
Now I would like to use this new feature when a function in my Symfony project returns a Doctrine entity. So I tried to declare a function like this:
public function getEntity(array $conditions, string $entityClass): ?object
{
// some logic...
return $queryBuilder->setMaxResults(1)->getQuery()->getOneOrNullResult();
}
As you can see it must return null
or object
variable. However, it seems that object
doesn't work as expected because I got an exception:
Type error: Return value of HelperBundle\\MyHelper::getEntity() must be an instance of HelperBundle\\object or null, instance of AppBundle\\Entity\\MyEntity returned
I'm actually not sure about what this message means: should returned object derive from a class located in HelperBundle
or what?
But generally speaking, is there a way to declare a return type for a generic Doctrine entity without using custom base classes or interfaces?
I've just now read an article about this and it's not supported to have a return type-hinting as object
You can however in PHP 7.2: http://php.net/manual/en/migration72.new-features.php
To address you first question, I will just say that this declaration
public function getEntity(array $conditions, string $entityClass): ?object
is understood by PHP <7.2 as if you declared object
class in HelperBundle
namespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.