Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php default arguments

In PHP, if I have a function written like this

function example($argument1, $argument2="", $argument3="")

And I can call this function in other place like this

example($argument1)

But if I want to give some value to the thrid argument, Should I do this

example($argument1, "", "test");

Or

 example($argument1, NULL, "test");

I think both will work but what is the better way? Because in future if the value for the $argument2 is changed in the main function and if I have "", then will there be any problem? Or NULL is the best option?

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Passing null or "" for a parameter you don't want to specify still results in those nulls and empty strings being passed to the function.

The only time the default value for a parameter is used is if the parameter is NOT SET ALL in the calling code. example('a') will let args #2 and #3 get the default values, but if you do example('a', null, "") then arg #3 is null and arg #3 is an empty string in the function, NOT the default values.

Ideally, PHP would support something like example('a', , "") to allow the default value to be used for arg #2, but this is just a syntax error.

If you need to leave off arguments in the middle of a function call but specify values for later arguments, you'll have to explicitly check for some sentinel value in the function itself and set defaults yourself.


Here's some sample code:

<?php

function example($a = 'a', $b = 'b', $c = 'c') {
        var_dump($a);
        var_dump($b);
        var_dump($c);
}

and for various inputs:

example():
string(1) "a"
string(1) "b"
string(1) "c"

example('z'):
string(1) "z"
string(1) "b"
string(1) "c"

example('y', null):
string(1) "y"
NULL
string(1) "c"

example('x', "", null):
string(1) "x"
string(0) ""
NULL

Note that as soon you specify ANYTHING for the argument in the function call, that value is passed in to the function and overrides the default that was set in the function definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...