嗨,我有疑问是否可以添加函数的默认参数作为其他函数的结果?例如:
static function addParameter(){
return rand(10,100)
}
function doSomething($year=$this->addParameter()) or
function doSomething($year=class::addParameter())
我需要将实际的年份和月份传递给我的函数。当我通过时
函数($month=3, $year=2016)
然后它可以工作,但我不想手写这个,而是想使用函数或其他东西来始终返回实际的月份和年份。
简短的回答:不,你不能。http://php.net/manual/en/functions.arguments.php 指出:
默认值必须是常量表达式,而不是(例如)变量、类成员或函数调用。
您可以使用默认的 null 值(如果通常函数不取一个)并检查参数是否为 null,然后从函数中获取值:
function testfun($testparam = null) {
if ($testparam == null) $testparam = myclass::funToReturnParam();
// Rest of function body
}
Yo 可以这样实现它
<?php
class Core {
static function addParameter(){
return rand(10,100);
}
}
$core = new Core();
function doSomething($rand){
echo 'this is rand '.$rand;
}
doSomething(Core::addParameter());
您可以根据需要更改函数定义。希望对:)有所帮助
来自 PHP 手册(强调我的):
默认值必须是常量表达式,而不是(例如)变量、类成员或函数调用。
所以只允许标量类型(布尔值、整数、字符串等)、数组和null
。
解决方法可能是检查参数是否为 null 并在函数中设置它:
function doSomething($year = null) {
if (!$year) {
$year = addParameter();
}
//actually do something
}