How to param/return class<T>
or null
with generics
#10238
-
Hi!, I'm trying to achieve something, but I don't know the correct solution. Be it with generics, or just a different implementation. Playground link: https://phpstan.org/r/f302f0b0-728e-4106-8670-5145a99eaac9 What Im trying to do:
Im trying to do this via generics on the interface: /**
* @template T of array<string, mixed> | null
*/
interface DomainEventInterface
{
/**
* @param (T is null ? null : DomainEventMetadata<T>) $metadata
*/
public function __construct(
?DomainEventMetadata $metadata,
);
/**
* @return (T is null ? null : DomainEventMetadata<T>)
*/
public function getMetadata(): ?DomainEventMetadata;
} If |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Yeah, right now PHPStan does not understand what you're trying to say with this constructor parameter: There's no PHPDoc tag to instruct PHPStan "infer T as something when doing What I tried for your example is a "null object" pattern. Basically don't have |
Beta Was this translation helpful? Give feedback.
Yeah, right now PHPStan does not understand what you're trying to say with this constructor parameter:
(T is null ? null : DomainEventMetadata<T>)
There's no PHPDoc tag to instruct PHPStan "infer T as something when doing
new Foo()
".What I tried for your example is a "null object" pattern. Basically don't have
null
in your code but treat "exists" and "does not exist" scenario the same way from the interface PoV: https://phpstan.org/r/640316e7-ab4f-4366-a1ff-734646f15268