问题
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