dqzuo0327 2014-05-05 09:49
浏览 217
已采纳

PHP函数,null默认参数

I have a PHP function signature that looks like this, where I want the 4th param to be NULL by default if nothing is supplied.

testfunction($param1, $param2, $param3, $param4=NULL) {
    //do stuff
}

I can also call using 4 params as such

x = testfunction('100', 'abc', 'xxx', null);

Why is it that I can also call the function using 3 parameters without any errors?

x = testfunction('100', 'abc', 'xxx');

Is what i'm doing even correct (using 3 params)? Any thoughts about how this relates to traditional method overloading where separate function signatures are defined?

My question is general in nature. Hope someone can shed some light on and around it.

  • 写回答

1条回答 默认 最新

  • drk49438 2014-05-05 10:02
    关注

    When you declare a function like this:

    testfunction($param1, $param2, $param3, $param4=NULL) {
        //do stuff
    }
    

    You're telling PHP that $param4 already has a value, so when that function is called, a value is already assigned to it. It doesn't expect you to send an argument for that parameter because a default one has already been assigned.

    It therefore knows the function will be able to operate (to a certain extent) as it should. It's useful for making optional parameters.

    However when you declare a function as this:

    testfunction($param1, $param2, $param3, $param4) {
        //do stuff
    }
    

    PHP Expects you to send through that argument ($param4), because without it, the function won't be able to accomplish what you've set it out to do, at least so PHP assumes, because you would never create a function with 4 parameters where not one of them are used in the function body.

    Make sense?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么