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 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误