dongyupan4850 2016-10-03 15:59
浏览 64
已采纳

参数是数组还是可调用时如何执行函数?

Look this example code:

I'm getting the error:

Fatal error: Uncaught Error: Cannot use object of type Closure as array in C:\xampp\htdocs\dermaquality\test.php:11 Stack trace: #0 C:\xampp\htdocs\dermaquality\test.php(20): test(Object(Closure)) #1 {main} thrown in

$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;

How can I call $func if $func is function or if $func['hello'] is function?

Thanks.

  • 写回答

1条回答 默认 最新

  • dongshi9407 2016-10-03 16:07
    关注

    Problem is in if (is_callable( $func['hello'] )) { because you dont know if $func is an array.. btw you dont put array as parameter in test( $array['hello'] ); you put just function...

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ROS Turtlebot3 多机协同自主探索环境时遇到的多机任务分配问题,explore节点
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题