繁体   English   中英

PHP可选函数参数

[英]PHP Optional Function Arguments

我有点难以尝试创建一个带有单个可选参数的函数。 我希望它不是函数的结果,而不是字符串(或者更好的是DateTime对象)。 本质上,我希望用户要么传递DateTime对象,要么如果没有提供任何参数,则让该函数求助于今天的日期。 PHP有可能吗? 通过尝试像这样在函数头中创建新对象

function myDateFunction($date = new DateTime()){
//My function goes here.
}

导致PHP崩溃。

非常感谢。

默认值必须是一个常量表达式,而不是(例如)变量,类成员或函数调用。

http://php.net/manual/zh/functions.arguments.php#example-154

是。 如果将$date实例移动到函数体,则是可能的:

<?php
header('Content-Type: text/plain');

function myDateFunction(DateTime $date = null){
    if($date === null){
        $date = new DateTime();
    }

    return $date->format('d.m.Y H:i:s');
}

echo
    myDateFunction(),
    PHP_EOL,
    myDateFunction(DateTime::createFromFormat('d.m.Y', '11.11.2011'));
?>

结果:

15.09.2013 17:25:02
11.11.2011 17:25:02

php.net

类型提示允许NULL值

您可以这样操作:

function myDateFunction($date = null){
    if(is_null($date) || !($date instanceof DateTime)) {
        $date = new DateTime();
    }

    return $date;
}

var_dump(myDateFunction());

您可以使用其他选项:

function myDateFunction($date = null){
 if(is_null($date)) $date = new DateTime();

}
function myDateFunc($date = null){
   if(!isset($date) || $date !instanceof DateTime){
     $date = new DateTime()
   }
   /* YOur code here*/
}

对于函数中的可选参数,您可以编写如下代码

function myDateFunction($date = ''){
         //My function goes here.
         if($date==''){ $date = new DateTime()}
    }

希望能帮助到你

暂无
暂无

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

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