【问题标题】:How to execute function when parameter is array or callable?当参数是数组或可调用时如何执行函数?
【发布时间】:2017-02-11 15:25:07
【问题描述】:

看看这个示例代码:

我收到了错误:

致命错误:未捕获错误:不能在 C:\xampp\htdocs\dermaquality\test.php:11 中使用闭包类型的对象作为数组:11 堆栈跟踪:#0 C:\xampp\htdocs\dermaquality\test .php(20): test(Object(Closure)) #1 {main} 抛出

$array = array(
    'hello' => function() {
        echo "HEllo world";
    }
);

function test( $func )
{
    if (is_callable( $func['hello'] )) {
        $func['hello']();
    }
    else {
        $func();
    }
}

echo "Executing 1 <br/>";
test( $hello = function() {"Hello world";} );
echo "Executing 2 <br/>";
test( $array['hello'] );
exit;

如果$func 是函数或$func['hello'] 是函数,我如何调用$func

谢谢。

【问题讨论】:

  • 尝试改变 if 做相反的事情: if (is_callable($func)) $func;否则 $func['hello']();

标签: php arrays function closures callable


【解决方案1】:

问题出在if (is_callable( $func['hello'] )) {,因为你不知道$func 是否是一个数组。顺便说一句,你没有将数组作为参数放在test( $array['hello'] ); 中,你只是把函数放在...

function test( $func )
{
    if (is_callable($func)) {
        $func();
    }
    else if (is_array($func)){
        if(isset($func['hello']) && is_callable($func['hello'])){
            $func['hello']();
        }else{
            // unknown what to call
        }
    }else{
        // unknown what to call
    }
}

【讨论】:

  • is_callable 只是函数,永远不知道是否调用了另一个函数,首先is_callable($func) 并不重要变量$func 中的值是什么,因为函数is_callable 将检查它是否可调用,在你使用$func['hello']之前你必须知道$func是一个数组,这就是为什么
  • 只是变量的值会通过参数传递给函数,所以some_function([]);在函数上下文中与$array = []; some_function($array);相同
  • 当你写$func['hello']时,你读取数组$func的值,键为hello,如果$func不是数组,则会发生错误
  • 试试$string = 'test'; $string[0];$array = ['test']; echo $array;$array = ['test']; $array['whatever'];之类的方法,它们都会失败...
  • 这意味着值的类型对于函数很重要,因为它们只知道如何处理它们准备工作的类型
猜你喜欢
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 2018-02-12
  • 1970-01-01
  • 2017-11-18
相关资源
最近更新 更多