如何将PHP函数的参数设置为默认值 [英] How to set a PHP function's param to a variable as the default value

查看:234
本文介绍了如何将PHP函数的参数设置为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我希望能够根据变量是真还是假来开启或关闭某个功能。这个函数仍然会执行,但是因为这个变量是false,所以它不会做例程。



类似于这个

  $ testTF =T; 

函数Test($ test = $ testTF){
echo $ test;
}

测试(Go);

当然,这不起作用,但我想知道是否有办法让它工作像打算一样。这个函数遍布在脚本中的任何地方,并且需要在某些地方,所以我不能将它们全部组合在一个if语句中,因为它会破坏它们。



我知道你可以在每次调用它时将值作为一个标志传递,但是我正在寻找一种方法来让它将该值作为默认值,除非另有说明。也许我正在寻找全局变量,但是我知道这很危险。



谢谢

解决方案

  $ testTF =T;您可以这样做吗? 

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

测试(Go);

或者,如果您反对使用全局变量,则可以将默认值封装在函数中,如($ test === NULL){

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

测试(Go);

函数getDefault(){
//从任何地方拉取默认值
$ testDefault ='T';
return $ testDefault;
}


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

解决方案

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;
}

这篇关于如何将PHP函数的参数设置为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆