Handling '0 references' for php callbacks in visuel studiio code when

131 views Asked by At

When editing wordpress code in Visual Studio Code,
if I have a function definition and than I use it as a callback for a call to add_action or add_filter like this:

function myCallback() {
    //do some stuff
}

add_action('init', 'myCallback') ;

but because its used as a string its not counted as a reference to the function and the intelisense says 0 references above my function which is true to some degree but also false and misleading in the practical sense.

Can I do something to tell visual studio code to add a reference to that function?

I was hoping I maybe could do something like (This is not real working code...):

function myCallback() {
    //do some stuff
}

add_action('init', myCallback.name) ;

i.e. get the name of myCallbck by referencing a member field or method of it.

or (This is again not a currently working solution - just an idea...)

add_action('init','myCallback' /* @references:myCallback */)     

i.e. by adding some comment that intelephanse could use to understand that there is a reference this it would otherwise miss.

2

There are 2 answers

4
shingo On

If you are using PHP 8.1, you can use the first class callable syntax

add_action('init', myCallback(...));

I tried DEVSENSE's PHP extension, the following callable form can be recognized as a reference.

class Foo {
    public static function myCallback() {}
}

add_action('init', [Foo::class, 'myCallback']);
4
Nanne On

You can use a callback to assign your function to:

$callable = function() {
   echo 'Hello world!';
};

call_user_func($callable);

The variable $callable has the type callable, and call_user_func has an argument of the type callable, just like add_action.

You can use that like so:

add_action('init', $callable);

This works for several versions: https://3v4l.org/1tH3K
If I read 3v4l.org right, it works for

5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.23, 8.2.0 - 8.2.10