0

The title may be a bit confusing, so let me explain. I have a class and a method. That that method itself has a function. Like this:

class MyClass {
   public static function my_function($param) {
      function nested_function() {
        //do something with $param
      }
   }
}

So my question is, how can I access $param in nested_function?

EDIT

The reason I'm doing this is because of a wordpress thing. I need something like this:

class MyClass {
   public static function my_function($param) {
      function nested_function() {
        //do something with $param
      }

      add_action('init', 'nested_function');
   }
}
2
  • 1
    function nested_function($param) use ($param) { // code here } Commented Sep 12, 2012 at 13:06
  • @N.B. Does not work with named global functions. Commented Sep 12, 2012 at 13:10

1 Answer 1

4

This is not a sensible thing to do. All named functions in PHP are global. Nesting them inside something else just makes their declaration conditional. I.e. you cannot call nested_function until you have called MyClass::my_function. And afterwards you cannot call MyClass::my_function again, because PHP will try to redeclare an existing function.

Maybe you want a closure, i.e. an anonymous function, which can include variables from the parent scope:

public static function my_function($param) {
    $nested_function = function () use ($param) {
        //do something with $param
    };
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi! Thank you, the reason why I'm doing this is because I'm doing a wordpress thing. And I need to use the add_action. I will update my question.
That seems like a terrible convention Wordpress has there which does not allow objects or anonymous functions as callback. You can try if class methods work, e.g. 'MyClass::some_callback', then you can pass the variable through a class property. Otherwise it seems only global can help you (shudder).
Well the anonymous function did actually work! Thank you! One question though, from what php version is this going to work?
Anonymous functions where introduced in PHP 5.3.

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.