JSowa
JSowa

Reputation: 10682

How to get static return type of a class method in PHP?

I have the following interface A and classes B and C (with PHP8.0 static return type):

interface A {
    public function getSomething(): self;
}

class B implements A {
    public function getSomething(): self
    {
        return $this;
    }
}

class C implements A {
    public function getSomething(): static
    {
        return $this;
    }
}

How to get the return type of method getSomething() of a new instance? Is it possible with ReflectionClass class?

$classes = [ 'B', 'C'];

$newClass = $classes[array_rand($classes)];

print((new ReflectionClass(new $newClass()))->getMethod('getSomething')->getReturnType());

My example returns self or static which is not my desired output. I want to get a concrete name class (A, B etc.) instead. Is it possible explicitly without any workaround?

Upvotes: 2

Views: 1689

Answers (2)

Pavel Železný
Pavel Železný

Reputation: 310

Great solution is a part of the "Nette framework" dev-stack, that provides Nette\Utils\Reflection helper.

More info here: https://doc.nette.org/en/utils/reflection#toc-getreturntype

Upvotes: 5

JSowa
JSowa

Reputation: 10682

After investigation it's not possible. ReflectionClass returns only defined return type, not real one when using types: static or self (A. B, etc.)

Upvotes: 0

Related Questions