doukanxi4246 2012-05-24 04:13
浏览 63
已采纳

如何将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>
  • 写回答

3条回答 默认 最新

  • dongzj2015 2012-05-24 04:15
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图