【问题标题】:How to specify default function parameter which is a function in PHP?如何指定默认函数参数,它是 PHP 中的函数?
【发布时间】:2019-11-16 01:45:54
【问题描述】:

我想知道如何指定参数的默认值,它应该是一个函数?我尝试通过以下函数闭包来做到这一点:

function foo($func = function(){}) {
    $func();
}

function bar() {
    $this->foo(); // Default parameter is supposed to be here

    $this->foo(function(){
        echo("non default func param");
    });
}

这会导致消息出现语法错误

“不允许将表达式作为参数默认值”。

【问题讨论】:

  • 为什么不:在 foo() 函数中调用函数..然后将结果返回到 function()
  • 在您的问题中分享实际代码示例
  • @devpro,我很难理解您的回复,如果您有任何代码 sn-ps,我将不胜感激。至于实际示例,我的 OP 中的 sn-p 是我的实际示例。
  • 你不能影响null默认值,然后检查它的影响吗?喜欢function foo ($fn = null) { if (is_callable($fn) { $fn(); } else { /* default process here */ } }

标签: php function closures


【解决方案1】:

一种解决方法是将默认参数设置为null,然后检查该参数是否实际上为空 - 如果是,则定义一个“默认”函数来代替使用。

然后检查参数是否可调用-如果不可调用,则引发异常-否则,调用函数!

function foo($func = null) {
    // If $func is null, use default function
    if ($func === null) {
        $func = function() {
            echo "Default!\n";
        };
    }
    // Verify that whatever parameter was supplied is a valid closure
    if (!is_callable($func)) {
        throw new Exception('Invalid parameter supplied');
    }
    // Call the function!
    $func();
}

function bar() {
    foo(); // Default parameter is supposed to be here

    foo(function(){
        echo "Non default func param \n";
    });
}

bar();

上面的输出是

默认!
非默认函数参数

【讨论】:

  • 我也有同样的想法。一个问题,你为什么不使用is_callable() 来检查$func 是否是一个函数?你的方法有更多的优势吗?
  • 这是一个很好的解决方法。谢谢你。遗憾的是 PHP 没有内置功能来为高阶函数提供默认函数参数。
  • 它可能也可以,我没有具体原因说明我为什么不使用is_callable() - 至少在可读性方面可能更好!
  • @Qirel - 哦,很高兴知道有什么不同!如果 PHP 的版本足够新,我想你可以写foo(?Closure $func = null) 而不是验证参数是否有效闭包。
  • @KévinBibollet 类型提示或类型声明是在 PHP5 中引入的,如 per the docs。但是可以捕获抛出异常,给定的错误类型将导致您无法恢复的致命错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 2011-03-24
  • 2016-12-12
  • 2012-06-14
  • 2012-02-03
相关资源
最近更新 更多