dtgr3392 2014-03-04 17:45
浏览 48
已采纳

直接从PHP数组调用函数

I am trying to call a PHP function via an array like so:

$x = (object) array(
    "one" => "value",
    "two" => "value2",
    "three" => function() {
        return "return_value";
    }
);

echo($x->three());

From this I receive the error:

<b>Fatal error</b>:  Call to undefined method stdClass::three()

I've searched a bit and cannot find any documentation on this, however I ran this through

php -l filename.php

which found no syntax errors.

I would like to know if what I'm trying to do is possible (end goal is to call a function with parameters from an array). Is anybody able to shed some light on this?

Thanks

Note, I have also tried:

function foo() {
    return "bar";
}
$x = (object) array(
    "foo" => foo
);
...

which leads to the same result.

  • 写回答

2条回答 默认 最新

  • doushuangdui5419 2014-03-04 18:23
    关注

    The type of method you created is classified as an anonymous function and is represented by the Closure class and thus inherits its properties, which includes the invoke method as specified by Amal Murali.

    You have two ways of calling this function:

    1. echo $x->three->__invoke();
    2. echo call_user_func( $x->three );

    If you need to pass arguments, you can call $x->three->__invoke( $args ); or call_user_func( $x->three, $args1, $args2 );.

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

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建