简体   繁体   中英

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)

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:

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):

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.

A workaround could be to check if the parameter is null and set it within the function:

function doSomething($year = null) {
    if (!$year) {
        $year = addParameter();
    }
    //actually do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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