PHPStorm Dynamic static method typehint

How can I tell PhpStorm two (2) things:
#1 that the dynamic method (static or not) does exist
#2 return type and parameter types of the dynamic method

Example:

X::register('plus', function($a,$b) { return $a+$b; } );
echo X::plus(1,2), "\n";

In which X is something like this:

class X {
static $functions = [];
private function __construct() {}
public static function register($name,$callback) { X::$functions[$name]=$callback; }
public static function __callStatic($name,$arguments) { return call_user_func_array(X::$functions[$name], $arguments); }
}

 

9 comments
Comment actions Permalink

Posted a bit too quickly. Currently the problem is that PhpStorm is complaining about the missing methods. 

0
Comment actions Permalink

I know, I could do it like this, but that's not very dynamic. I am looking for something that could be written along with the code that actually adds the dynamic method. X is external, so I can not (nor do I want to) change that file. 

/**
* @method static plus(int $int, int $int1)
*/
class X {
0
Comment actions Permalink

If I only could do this:

/**
*
* @method static int X::plus(int $int, int $int1)
*/
X::register('plus', function($a,$b) { return $a+$b; } );

or this

/**
* @class X
* @method static int plus(int $int, int $int1)
*/
X::register('plus', function($a,$b) { return $a+$b; } );

Or maybe I am missing something?

0
Comment actions Permalink

Hi there,

You cannot do that with PHPDoc in the middle of the code (ad-hoc). This can only be done at the class declaration level.

What you can do is declare your own X class with all such methods defined there, place such file in subfolder that will be used by the IDE only.

This is how https://github.com/barryvdh/laravel-ide-helper does when it describes such dynamic/magic methods in Laravel (Laravel has a lot of magic methods where you call static method but in reality it makes a call to the instance method, Laravel facades, Macroable classes (the same as your code); this package it creates a file named _ide_helper.php with all the stuff inside).

P.S. By default PhpStorm will complain on such "multiple class declarations", but that inspection can easily be disabled.

1
Comment actions Permalink

Thanks. I was afraid that this might be the current state of things. 

Shame really, it is so close. It does recognize it as a static method "::plus(..)", only the class is missing. One day, perhaps. 

 

 

0
Comment actions Permalink

You can also submit this to our tracker at https://youtrack.jetbrains.com/newIssue as a new feature request. The idea looks interesting.

1

Please sign in to leave a comment.