php 7 中函数定义中的默认可调用

Default callable in function definition in php 7

我有一个带有 2 个参数的函数:一个字符串和一个可调用对象。 我希望可调用对象是可选的。见下文。

function saySomething($str, $callback){

    echo $str;

    $res = false;
    if(is_callable($callback)){
        $res = $callback();
    }

    if($res){
        echo ', I am cool';
    } else {
        echo ', I am not cool';
    }
}

// This works as I expect
saySomething('piet');// deliberately not supplying a callback
// I want the output to be: piet, I am not cool.
// The output in this case: "piet, I am not cool."

在 php 5.4 和 php 7 中,可以在函数参数中声明/类型提示一个可调用对象。函数体中不再需要 is_callable 了。接下来,如果这样做,那么可调用参数必须有效,因此它不再是可选的。

我想要什么?

我想知道是否可以使用可调用类型声明但将其保留为可选参数。

我试过这个:

// This is not possible :-(
// Fatal error: Uncaught ArgumentCountError: Too few arguments to function saySomething()
function saySomething($str, callable $callback = function(){return false;}){

    echo $str;

    $res = $callback();
    if($res){
        echo ', I am cool';
    } else {
        echo ', I am not cool';
    }
}

saySomething('piet'); // deliberately not supplying a callback
// I want the output to be: piet, I am not cool.

当客户端代码未提供可调用对象时,我希望将可调用对象设置为 return false。

可能的重复项 没有针对这种情况提供解决方案。

唯一接受的可调用默认参数是 NULL。这是部分记录的,但它既没有明确记录也没有完全记录(据我所知)。从手册中综合,您可以得出结论,不允许使用匿名函数。其他有效的可调用类型也不允许作为可调用提示参数的默认值,但这不在手册中(据我所知)。

function arguments manual page states that only scalars, arrays and NULL can be default arguments. Callables can be objects (Closure or objects with an __invoke method), 2 element arrays (a class or object and a method name) or strings. Objects aren't scalars (as stated on the is_scalar 手册页),因此不能用作默认参数(排除匿名函数),即使是未类型化提示的参数。脱离手册,这似乎允许可调用参数的字符串和数组默认值,但如果您尝试使用字符串或数组,PHP 会给出错误:

Default value for parameters with callable type can only be NULL

虽然数组和字符串(通常)允许作为默认值,但它们不能总是在编译时针对可调用对象进行类型检查;它们可能引用尚未定义的可调用对象,导致类型检查产生假阴性。我怀疑正因为如此,它们被排除在可调用对象的默认设置之外。

如果你想有一个可选的可调用参数,你必须使用NULL作为默认值,然后在函数内测试变量。既有可选参数又不测试参数的要求是不兼容的。