Accessing the variables from a PHP Anonymous Function

故事扮演 提交于 2020-01-15 05:08:27

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/15248745/accessing-the-variables-from-a-php-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!