Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

PHP - Make reference parameter optional?

Say I've defined a function in PHP, and the last parameter is passed by reference. Is there any way I can make that optional? How can I tell if it's set?

I've never worked with pass-by-reference in PHP, so there may be a goofy mistake below, but here's an example:

$foo;
function bar($var1,&$reference)
{
    if(isset($reference)) do_stuff();
    else return FALSE;
}

bar("variable");//reference is not set
bar("variable",$foo);//reference is set
question from:https://stackoverflow.com/questions/16636725/php-make-reference-parameter-optional

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Taken from PHP official manual:

NULL can be used as default value, but it can not be passed from outside

<?php

function foo(&$a = NULL) {
    if ($a === NULL) {
        echo "NULL
";
    } else {
        echo "$a
";
    }
}

foo(); // "NULL"

foo($uninitialized_var); // "NULL"

$var = "hello world";
foo($var); // "hello world"

foo(5); // Produces an error

foo(NULL); // Produces an error

?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...