1

I am using VSCode and PHP 8.1+. In standard way, we can get hints when we type $myClass->??? and we will get a list of functions within the class.

However, recently I have a class that could dynamically instantiate other class within the $myClass. I would like to get also the hints of the dynamically instantiate classes. For example $myClass->otherClass()->?? could get a lists of functions of OtherClass.php. Is there anywhere I could specify the rules to let IDE knows?

The following is a sample condition

class myClass{
  public $helpers = [];
  public function __call($helper, $args)
    {
        if(array_key_exists($helper, $this->helpers)){
            return $this->helpers[$helper];
        }
        
        $class = 'App\Services\Helpers\\' . ucfirst(str($helper)->camel()) . "Helper";
        if (class_exists($class)) {
            $this->helpers[$helper] = new $class($this, ...$args);
            return $this->helpers[$helper];
        }

        throw new \RuntimeException("Class {$class} does not exist");
    }
}

Usage:

$myClass = new myClass;
$myClass->test()->??? //showing hints of App\Services\Helpers\TestHelper class

I have read this thread but seem cannot be solved. PHP Code Hinting Dynamically Created Classes

Update

This is a closer one I can get. But it still require me to add all possible classes and methods.

/**
 * @method \App\Services\Helpers\TestHelper test()
 * @method \App\Services\Helpers\Test2Helper test2()
 * ....
 */
class myClass{
  public $helpers = [];
  public function __call($helper, $args)
    {
        if(array_key_exists($helper, $this->helpers)){
            return $this->helpers[$helper];
        }
        
        $class = 'App\Services\Helpers\\' . ucfirst(str($helper)->camel()) . "Helper";
        if (class_exists($class)) {
            $this->helpers[$helper] = new $class($this, ...$args);
            return $this->helpers[$helper];
        }

        throw new \RuntimeException("Class {$class} does not exist");
    }
}

0

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.