简体   繁体   中英

How to clone a child class instance within a parent class method

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 hints 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?

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM