doujiang1832 2014-01-24 14:01
浏览 66
已采纳

PHP函数byref参数的默认值

I have a PHP function that I have been asked to update as business needs have changed. The original function worked like this.

function myFunction($var1, $var2, $var3) {
   CODE GOES HERE
}

For the new version, a fourth optional parameter is required. I know that I can do this like this:

function myFunction($var1, $var2, $var3, $var4 = "") {
    CODE GOES HERE
}

I created the new code and it works fine. I've just been informed that when a value is passed in for the last parameter, it needs to be byref. I searched the PHP documentation and questions here but haven't seen anything about the possibility of this. I would assume the code would work like this:

function myFunction($var1, $var2, $var3, &$var4 = "") {
    CODE GOES HERE
}

Will this work? Does PHP allow a variable to be passed by ref and also have a default value set for it if nothing is passed in?

  • 写回答

1条回答 默认 最新

  • douzi2749 2014-01-24 14:04
    关注

    Yes, it does work.

    Have a look here at ideone.com to see it in action.

    <?php
    
    function test(&$var = "test") {
        echo $var;
    }
    
    test();
    

    Outputs

    test
    

    However, there is a caveat. If you do pass a parameter, it needs to be a reference to a variable. The following will not work:

    test("Testing");
    

    Because "Testing" is a literal string, not a referable variable.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?