1

I'm trying to use the variable $args_array inside an anonymous function that and a regular function.

The variable is declared at the top level, and yet I receive an error about this variable not being defined when I try to use it in these functions.

This is the warnings I get in my IDE: enter image description here

And this is my code:

$args_array = array(
    'endpoint' => 'my_endpoint',
    'url' => 'my_url',
    'api_key' => 'my_api_key',
    'api_value' => 'my_api_value'
);

add_action( 'rest_api_init', function () {
    register_rest_route( 'api', '/semir/', array(
        'methods' => 'GET',
        'callback' => 'semirs_function',
        'args' => $args_array
    ));
});

function semirs_function() {
    return $args_array;
}
yivi
  • 42,438
  • 18
  • 116
  • 138
  • 4
    that function resets the variable scope. You need to declare that `$args_array` inside the function callback – treyBake Aug 20 '19 at 15:36

1 Answers1

0

That variable ($args_array) falls out of scope when running inside the action hook callback.

You need to inherit the variable from the parent scope by using the use construct.

E.g.:

add_action( 'rest_api_init', function() use( $args_array ) {
    register_rest_route( 'api', '/semir/', [
        'methods' => 'GET',
        'callback' => 'semirs_function',
        'args' => $args_array
    ]);
});

Since you are using yet another function that needs to use that variable to return it, you need to pass it to that one so it's part of its scope:

function semirs_function($args) { return $args; }
yivi
  • 42,438
  • 18
  • 116
  • 138
  • 1
    That is understandable, I'm trying to print out the array endpoint, url, api_key, api_value - I will look into this and see what is causing it. –  Aug 20 '19 at 16:11
  • Great. I'm sure you'll find it soon. If you can isolate the problem maybe you can ask a new question about that (if you can't solve it on your own, which you probably can). Good luck! – yivi Aug 20 '19 at 16:12