Get the IDE to dynamically refer to the constructor when calling a static method

Let's say i have a parent and a child class like that:

class Component {

    public function __construct(string $string)
    {
        //...
    }

}

class ChildComponent  extends Component {

    public function __construct(string $string, array $args)
    {
        //...
    }
}

Now I would like to implement a static method to instantiate classes, like that:

class Component {

    public function __construct(string $string)
    {
        //...
    }

    public static function create(...$args): static
    {
        return new static(...$args);
    }
}

Is there a way to have the IDE suggest the expected arguments of the static::class (even if only the constructor annotations), maybe with PHP 8 attributes ? This is what I would like to have:


Component::create() // IDE refers to the constructor of "Component" ($string expected)
ChildComponent::create() // IDE refers to the constructor of "child component" ($string and $array expected)

Please avoid"

why would you do that anyway ...

or

Just define the "static create" on each child

Edit: "new" method renamed "create" for clarity purposes



Read more here: https://stackoverflow.com/questions/67378768/get-the-ide-to-dynamically-refer-to-the-constructor-when-calling-a-static-method

Content Attribution

This content was originally published by Jess_Pinkman at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: