简体   繁体   English

在回调匿名函数中访问类的实例

[英]Access instance of class in callback anonymous function

I have a class with a few methods that take an anonymous function as a parameter. 我有一类带有一些将匿名函数作为参数的方法的类。 The class looks like this: 该类如下所示:

class MyClass {
    public function myMethod($param, $func) {
           echo $param;
           user_call_func($func);
    }


    public function sayHello() {
        echo "Hello from MyClass";
    }
}

I'd like to be able to do things like this: 我希望能够做这样的事情:

$obj = new MyClass;
$obj->myMethod("Hi", function($obj) {
    echo "I'm in this anonymous function";
    // let's use a method from myClass
    $obj->sayHello();
});

So, in my anonymous function, since I passed $obj as a parameter to the anonymous function, I should be able to access its methods from within the anonymous function. 因此,在我的匿名函数中,由于我将$ obj作为参数传递给匿名函数,因此我应该能够从匿名函数内部访问其方法。 In this case we'd see 在这种情况下,我们会看到

I'm in this anonymous function
Hello from MyClass

How would I achieve this? 我将如何实现?

Thanks 谢谢

Use the use construct: 使用use构造:

$self = $this;
$obj->myMethod("Hi", function($obj) use($self) {
    echo "I'm in this anonymous function";
    // let's use a method from myClass
    $obj->sayHello();
});

You've got to capture $this in another variable because use doesn't allow $this to be passed in, unless you are using PHP >= 5.4. 您必须在另一个变量中捕获$this ,因为use不允许$this传入,除非您使用的是PHP> = 5.4。 Relevant quote from the documentation : 文档中的相关报价:

Closures may also inherit variables from the parent scope. 闭包也可以从父范围继承变量。 Any such variables must be passed to the use language construct. 任何此类变量都必须传递给use语言构造。 Inheriting variables from the parent scope is not the same as using global variables. 从父作用域继承变量与使用全局变量不同。 Global variables exist in the global scope, which is the same no matter what function is executing. 全局变量存在于全局范围内,无论执行什么功能,该变量都是相同的。 The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). 闭包的父作用域是在其中声明闭包的函数(不一定是从其调用的函数)。

Update 更新

It may also be helpful to know that you retain the visibility of the class that you're currently in when the anonymous function is executing, as demonstrated in this simple script: 如以下简单脚本所示,知道在执行匿名函数时保留当前所在类的可见性也可能会有所帮助:

class Test
{
    public function testMe()
    {
        $self = $this;
        $tester = function() use($self) {
            $self->iAmPrivate();
        };

        $tester();
    }

    private function iAmPrivate()
    {
        echo 'I can see my own private parts!';
    }
}

$test = new Test;
$test->testMe();

Output: 输出:

I can see my own private parts! 我可以看到自己的私人零件!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM