I have this:
class A {}
class B {}
class X
{
private function create(string $class) : object
{
return new $class();
}
public function createA() : A
{
return $this->create('A');
}
public function createB() : B
{
return $this->create('B');
}
}
And as the screenshot says:
What to set for return type to indicate that it is an "object"? Unfortunately A
and B
don't have anything in common (except that THEY BOTH ARE OBJECTS!!!!)
Has to be because object
can be ANY class instance, even B
etc.
You can annotate the create()
method with generics PHPDoc to tell that the return type will be the same as the input parameter class string. It gives more context info to the IDE.
/**
* @template T
*
* @param string $class
* @return T
*/
private function create(string $class) : object
{
return new $class();
}
P.S.
Instead of create('B');
better use create(B::class)
. This way the IDE can track the usages of that class for refactoring/search purposes etc.