[英]adding default parameters of the function as result of other function
Hi I have question it is possible to adding default parameters of the function as result of other function? 嗨,我有疑问是否可以将功能的默认参数添加为其他功能的结果? For example:
例如:
static function addParameter(){
return rand(10,100)
}
function doSomething($year=$this->addParameter()) or
function doSomething($year=class::addParameter())
I need to pass actual year and month to my function. 我需要将实际的年份和月份传递给我的职能。 When i pass
当我通过时
function($month=3, $year=2016)
函数($ month = 3,$ year = 2016)
it work then but i not want to write this from hand but want to use function or something to always return actual month and year. 然后工作,但我不想手写,但想使用函数或总是返回实际月份和年份的东西。
Short answer: no, you can't. 简短的回答:不,你不能。 http://php.net/manual/en/functions.arguments.php states that:
http://php.net/manual/zh-CN/functions.arguments.php指出:
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
默认值必须是一个常量表达式,而不是(例如)变量,类成员或函数调用。
You can use default null value (if normally function does not take one) and check if parameter is null, then get value from function: 您可以使用默认的空值(如果正常情况下函数不使用一个)并检查参数是否为空,然后从函数获取值:
function testfun($testparam = null) {
if ($testparam == null) $testparam = myclass::funToReturnParam();
// Rest of function body
}
Yo can implement it like this 哟可以这样实现
<?php
class Core {
static function addParameter(){
return rand(10,100);
}
}
$core = new Core();
function doSomething($rand){
echo 'this is rand '.$rand;
}
doSomething(Core::addParameter());
You can change the function defination according to your requirement. 您可以根据需要更改功能定义。 hope it helps :)
希望能帮助到你 :)
From the PHP Manual (emphasis mine): 从PHP手册 (重点是我的):
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
默认值必须是一个常量表达式, 而不是 (例如)变量,类成员或函数调用。
So only scalar types(boolean, int, string etc), arrays and null
are allowed. 因此,仅允许使用标量类型(布尔,整数,字符串等),数组和
null
。
A workaround could be to check if the parameter is null and set it within the function: 一种解决方法是检查参数是否为null并在函数中进行设置:
function doSomething($year = null) {
if (!$year) {
$year = addParameter();
}
//actually do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.