2

I have the following class with static variables. How can I access the static functions of a class from within an anonymous PHP function?

class MyClass {
  public static function MyFunction(mylocalparam){
      MyStaticClass:MyStaticMethod(function(myparam) use(mylocalparam){
         MyClass::MyFunction2(mylocalparam);
   });
  }

  private static function MyFunction2(someobject){
  }
}

I am having trouble accessing the function "MyFunction2" from within the anonymous class. Could you please advice on how to rectify this?

2 Answers 2

3

Not going to happen. You need to make the static function public. The anonymous function doesn't run inside the scope of MyClass, and therefore doesn't have access to private methods contained within it.

Sign up to request clarification or add additional context in comments.

Comments

1

Statically is not possible, but if you want you can pass the method you want to call via parameter as of type callback.

If you change the entire class to be an instance class (deleting all the static keywords) then you can use $this inside the anonymous function to call any method of the class you are in.

From the PHP manual:

Closures may also inherit variables from the parent scope.

As specified:

In version 5.4.0 $this can be used in anonymous functions.

class MyClass {
  public function MyFunction($mylocalparam){
      MyStaticClass:MyStaticMethod(function($myparam) use($mylocalparam){
         $this->MyFunction2($mylocalparam);
   });
  }

  private function MyFunction2($someobject){
  }
}

Comments

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.