douduan3203 2012-09-26 13:22
浏览 95
已采纳

类中的匿名函数

is there a better way to call an anonymous function inside a class? Here is a simple example that clearifies what I mean.

class foo
{
     private $call_back_1 = null;
     private $call_back_2 = null;

     function __construct($func1, $func2)
     {
          $this->call_back_1 = func1;
          $this->call_back_2 = func2;
     }


     function provokeCallBacks()
     {
          //this does not work, and gives an error  
          $this->call_back_1();


          //I would like to avoid this
          $method = $this->call_back_2;
          $method(); 
     }
}

$call1 = function(){ echo "inside call 1"};
$call2 = function(){ echo "inside call 2"};

$test = new foo(call1, call2);

$test->provokeCallBacks();

* Update 1: Please ignore any syntax error as I have written this on the fly for demo puposes. *

Inside foo:provokeCallBacks, I am trying to call the anonymous functions how ever the first way does not works and gives an error. The second one works but it's a bit stupid that I have to use a temp variable called "$method" to make the call.

I want to know if there exists a better way to call the anonymous function.

  • 写回答

5条回答 默认 最新

  • douyi9705 2012-09-26 13:27
    关注
    call_user_func($this->call_back_1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)