2014-06-05 40 views
0

如何从这个匿名函数中调用doSomethingElse函数?PHP从匿名函数中调用类函数

如果我尝试$这个 - > doSomethingElse()我得到“使用$这个时候不是在对象上下文”错误

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 

      } 
     }); 
    } 
} 
+0

更多关于匿名函数这不是有效的代码,目前还不清楚,你问究竟。 – deceze

+0

抱歉,不正确地复制了代码 – wot

+0

您使用的是哪个版本的PHP? – deceze

回答

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