如何将PHP函数的参数设置为变量作为默认值[重复]

This question already has an answer here:

So I'd like to be able to switch a certain function on or off depending on if a variable is true or false. The function would still execute, but because the variable is false, it won't do it's routine.

Something like this

$testTF = "T";

function Test($test=$testTF){
echo $test;
}

Test("Go");

Of course this won't work, but I'm wondering if there's a way to make it work like intended. This function is sprinkled everywhere in the script, and needs to be in certain places, so I can't just group them all together under one if statement because it would break them.

I know you could just pass the value as a flag every time you call it, but I'm looking for a way to make it assume that value as default unless told otherwise. Maybe I'm looking at globals here but that's dangerous I'm told.

Thanks

</div>

Could you do this?

$testTF = "T";

function Test($test=NULL){
    if ($test ===NULL) {
        global $testTF;
        $test = $testTF;
    }
    echo $test;
}

Test("Go");

Optionally, if you're against using globals, you can encapsulate the default value in a function, like this:

function Test($test=NULL){
    if ($test ===NULL) {        
        $test = getDefault();
    }
    echo $test;
}

Test("Go");

function getDefault(){
    //pull default value from wherever
    $testDefault = 'T';
    return $testDefault;
}

Short answer is the way you want to do it is impossible but this is also a duplicate of : PHP function with variable as default value for a parameter

Has the answer you were looking for :)

You could also do this with closures:

$testTF = 'T';

$Test = function ($test = null) use ($testTF){
    if ($test === null) $test = $testTF;
    echo $test;
};

$Test(); //T
$Test(null); //T
$Test('Go'); //Go