Dynamic return type

Hi :)

I have been looking for something which solves the following problem:

class Cloner {
    static function doClone($obj) {
      return clone $obj;

class Foo {
    function bar() {
        echo "bar code";

$foo = new Foo();
$fooCloned = Cloner::doClone($foo);

PHPStorm does not detect the type of the returned object $fooCloned, thus marking the last 'bar()' call as not found. Is there any way to make it able to know that each object returned by Cloner::doClone($foo) is of the same type $foo is?

I have been looking for similar scenarios and ended up with this thread, but wheter it doesn't fit what I need, or I'm omiting something.


Comment actions Permalink

Hi there,

Currently I do not see how it's possible (to do automatically) -- you do not provide any info that would help IDE to correlate the parameter with returned type.

In your case everything is dynamic ($foo variable as parameter for doClone() method) and IDE does not support any tags (which simply do not exist AFAIK) that would allow such type inheritance info (e.g. something like "@retun SameTypeAsInput").

You only choice right now is to manually provide such typehints:

/** @var Foo $fooCloned */
$fooCloned = Cloner::foClone($foo);

Comment actions Permalink

I was afraid that would be the answer :( Anyway, thanks a lot for your help!


Please sign in to leave a comment.