douningzhi1991 2011-06-08 11:28
浏览 12
已采纳

创建一个variable_function作为类的成员

Let's say we have a class stockFns and I do

$stockFns->{$functionOne}=create_function('$a,$b' , 'return $a+$b;');

This creates a property in $stockFns named whatever create_function returned.

Now I want to refer (invoke) to the created_function.

What would be a clean way to do it in a single instruction?. An example

$stockFns=new StockFns;
$functionOne='add';
$stockFns->{$functionOne}=create_function('$a,$b' , 'return $a+$b;');

//echo "***" . ($stockFns->add)(1,2);  // That doesn't work
$theFn=$stockFns->add;
echo $theFn(1,2);         // This works but reuires two instructions

Thanks!

  • 写回答

2条回答 默认 最新

  • doushui3061 2011-06-08 11:32
    关注

    Either your way, or

    echo call_user_func(array($stockFbs, 'add'), 1, 2);
    

    The problem is, that PHP cannot distinguish real methods from properties with callables. If you call something with () it will not touch the properties at all and in maybe will call __call, if it exists. You can try something like

    class StockFns {
      public function __call ($name, $args) {
        $fctn = $this->{$name};
        return call_user_func_array($fctn, $args);
      }
    }
    

    As a workaround, so __call() will redirect to your callback.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?