1

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?

4
  • What's your php version, everything seems correct 3v4l.org/HhjnA Commented Nov 9, 2021 at 20:26
  • Using v7.4. My IDE just gripes at me for using the wrong return type, so it won't provide hinting for my child class instances. Tried all sorts of PHPDoc hints and declaring :self return types, but to no avail. Commented Nov 9, 2021 at 20:29
  • Which IDE you are using? Please add this to your question. Commented Nov 9, 2021 at 20:29
  • 1
    @greeflas PHPStorm. Added to question Commented Nov 9, 2021 at 20:30

1 Answer 1

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

And in php8 you can public function doAThing(): static)
Oh god, it's always the most obvious thing once you see it. Leaving the question since I couldn't find any references to this anywhere. Knowing how to use PHPDoc fixes so much s***.
@u_mulder yes, thank you for the reminder. Slowly moving projects to php8. Most of mine are still <7.3.
It's a good question, but your title doesn't reflect what you actually wanted to know. A better title would have been: "Child class that calls parent method to return clone shows as parent class instance in PHPStorm." Even better would be to include the exact messaging you got from PHPStorm, because in the future, people will cut and paste the message into Google.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.