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.

图片转代码服务由CSDN问答提供 功能建议

我试图通过如下数组调用PHP函数:

  $ x =(object)array(
“one”=&gt;“value”,
“two”=&gt;“value2”,
“three”=&gt; function(){
 返回“return_value”; 
} 
); 
 
echo($ x-&gt; three()); 
   
 
 

从此我收到错误 :

 &lt; b&gt;致命错误&lt; / b&gt;:调用未定义的方法stdClass :: three()
   
 
  

我搜索了一下,找不到任何相关的文档,但我通过

  php -l filename.php 
   
 
 

没有发现语法错误。

我想知道我正在尝试做的是什么(最终目标是调用函数 来自数组的参数)。 是否有人能够对此有所了解?

谢谢

注意,我也尝试过:

  function foo(){
 return“bar”; 
} 
 $ x =(object)array(
“foo”=&gt; foo 
); \  ñ... 
   
 \  n 

导致相同的结果。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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条)

相关推荐 更多相似问题