繁体   English   中英

PHP函数作为函数的默认参数

[英]PHP Function as a Function's Default Parameter

我想知道是否有一种更简单的方法可以使用php内置函数作为函数的默认值。

这是我目前的代码:

function custom_date($format = 'm-d-Y', $time = null)
{
    if($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $time);
}

我想使用time()作为$time的默认参数而不是null ,但它不会让我。 我知道我可以将time()作为第二个参数传递给custom_date到处调用它,但它在没有第二个参数的许多地方使用并且改变它将是一个痛苦。

当没有传递给函数的值时,强制$time等于time()

function custom_date($format = 'm-d-Y', $time = null)
{
    $time = (null == $time) ? time() : $time;
    if($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $time);
 }

尝试这个。

function custom_date($format = 'm-d-Y', $func = 'time') {
if (function_exists($func)) {
    if ($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $func());
}elseif(is_numeric($func)){
    //timestamp logic
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM