5

Is there a way to document that a certain class has magic methods for every method defined in another class?

I am using PhpStorm, so I would be happy with any solution that will get autocomplete to work properly for that.

class A
{
    // a bunch of functions go here...
}

/**
 * Class B
 * What should go here to make it work???
 */
class B
{
    private $aInstance;

public function __construct() {
    $this->aInstance = new A();
}

public function __call($name, $arguments) {
    // TODO: Implement __call() method.
    if(method_exists($this->aInstance, $name)) {
        return $this->aInstance->{$name}(...$arguments);
    }
    throw new BadMethodCallException();
}

    // a bunch more functions go here...
}
Person93
  • 1,004
  • 8
  • 22
  • I think that `$this->aInstance->{$name}(...$arguments);` is deprecated in PHP 7.0 and later. Might need to use `call_user_func` there – Machavity Nov 07 '16 at 19:49
  • Also, why can't `B` just extend `A`? Would easily resolve the problem – Machavity Nov 07 '16 at 19:50
  • B already has a parent. – Person93 Nov 07 '16 at 19:56
  • 1
    Hmm, have you tried something similar to this question? http://stackoverflow.com/questions/15634021/how-to-document-magic-call-and-callstatic-methods-for-ides – Machavity Nov 07 '16 at 20:00
  • The only way to do this via PHPDoc is to list every method manually via `@method` as stated in the previous comment (will work in other editors/IDEs that support it). In PhpStorm though the `@mixin className` will also work .. which might do the job for you here. – LazyOne Nov 07 '16 at 20:43
  • Putting in every method manually is not workable. Whenever any method signature in class A is updated, I'd need to go back and fix B. – Person93 Nov 07 '16 at 22:49
  • The `@mixin` tag works.If you write an answer, I will accept it. Thanks! – Person93 Nov 07 '16 at 22:49

1 Answers1

5

The proper solution is to use supported @method PHPDoc tags. This way it will also work in other editors/IDEs that support PHPDoc and understand such standard tag.

This approach requires every method to be listed separately. More on this in another StackOverflow question/answer: https://stackoverflow.com/a/15634488/783119.


In current PhpStorm versions you may use not-in-PHPDoc-specs (and therefore possibly PhpStorm-specific) @mixin tag.

Adding @mixing className in PHPDoc comment for your target class should do the job for you.

/**
 * Class B
 * 
 * @mixin A
 */
class B
{

Basically, @mixin tag does what actual PHP's traits do.

Please note that there is no guarantee that support for such tag will not be removed at some point in the future, although it's pretty unlikely.

Community
  • 1
  • 1
LazyOne
  • 137,403
  • 37
  • 338
  • 342