";"/> ";">
Home >Backend Development >PHP Tutorial >Detailed explanation of the usage of parameter default values of PHP custom functions
Any valid PHP code may appear inside a function, even other function and class definitions.
Function names have the same naming rules as other identifiers in PHP. Valid function names begin with a letter or underscore, followed by letters, numbers, or underscores.
can be represented by regular expression as: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.
phpCustom functionWhen accepting parameters, you can directly assign default values
function TestStr($str) { return $str."是一个字符串"; } echo TestStr("abcdef")."</br>";
The above custom function accepts one parameter. If we call TestStr() ;What will happen if no parameters are given?
Report an error directly: Warning: Missing argument 1 for TestStr()
So in order to avoid the above errors during the development process, we generally have to customize Assign default values to the parameters when using the function, as follows
function TestStr2($str="kkkkk") { return $str."是一个字符串"; }
Now call TestStr2() without error, directly output kkkkk is a string, of course the default parameters will be replaced after you pass the parameters.
The third situation:
When there are more than 2 parameters, if not all default values are given, the default values must be given in order from right to left parameters. The following are wrong examples
function TestStr3($str ='mmmmm' ,$para) { return $str."和".$para."都是字符串"; }
The above does not give the default value from right to left, but the leftmost one gives a default value.
When we call the function TestStr3("First parameter" ); What we expect is that the first parameter is replaced by the default value, and the second parameter is replaced by the incoming parameter. But this is not the case. The order of replacing parameters is from left to right. So not only does the second parameter not have an incoming value , there is not even a default value, so an error is reported directly
The correct default value should be like this
function TestStr3($str,$para='mmmmm') { return $str."和".$para."都是字符串"; }
Then output:
The first parameter and mmmmm are both strings
The above is the detailed content of Detailed explanation of the usage of parameter default values of PHP custom functions. For more information, please follow other related articles on the PHP Chinese website!