Home > Mobile >  How to clone a child class instance within a parent class method
How to clone a child class instance within a parent class method

Time:11-10

I have a child class. My parent class has an instance method that clones $this and fluently returns the clone. I want to use that instance method with my child class instance, but I get errors in my IDE (PhpStorm) that the returned value is an instance of the parent class, not of the child class as I would have expected:

<?php
class myParentClass
{
    public function doAThing()
    {
        $clone = clone $this;
        // ... doing things
        return $clone;
    }
}

class myChildClass extends myParentClass {
    public function doTricks()
    {
        // ... do some tricks
    }
}

$myChild = new myChildClass();
$myChild = $myChild->doAThing(); // returns myParentClass instance, not myChildClass
$myChild->doTricks(); // Error, myParentClass doesn't have a doTricks() method

How can I get myChildClass::doAThing() to pass back a myChildClass instance?

CodePudding user response:

You can add following PHPDoc block and PhpStorm will known what object actually returned

class myParentClass
{
    /**
     * @return static
     */
    public function doAThing()
    {
        $clone = clone $this;
        // ... doing things
        return $clone;
    }
}
  • Related