简体   繁体   中英

PHP function byref parameter with default value

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM