Abishek
Abishek

Reputation: 11701

Accessing the variables from a PHP Anonymous Function

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?

Upvotes: 2

Views: 623

Answers (2)

Shoe
Shoe

Reputation: 76280

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){
  }
}

Upvotes: 1

Colin M
Colin M

Reputation: 13348

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.

Upvotes: 3

Related Questions