PHP从匿名函数中调用类函数

时间:2014-06-05 14:32:17

标签: php

如何从此匿名函数中调用doSomethingElse函数?

如果我尝试$ this-> doSomethingElse(),我会在不在对象上下文中时使用$ this'错误

class MyController extends AppController {

    public function doSomethingElse()
    {
        //do something
    }


    public function doSomething()
    {
        $this->Crud->on('afterSave', function(CakeEvent $event) {
            if ($event->subject->success) {

                    //how do I call 'doSomethingElse' from here

            }
        }); 
    }
}

1 个答案:

答案 0 :(得分:3)

在您的匿名函数之外引用您的MyController,并使用

class MyController extends AppController {

    public function doSomethingElse()
    {
        //do something
    }


    public function doSomething()
    {
        $reference = $this;

        $this->Crud->on('afterSave', function(CakeEvent $event) use ($reference) {
            if ($event->subject->success) {

                    //how do I call 'doSomethingElse' from here
                    $reference->doSomethingElse();

            }
        }); 
    }
}

在PHP5.4之后$this可以在匿名函数中使用,而不是在use (...)中将其作为引用传递。

详细了解php site

中的匿名功能
相关问题