I have defined a php function:
function my_function($text = '', $relative = false, $icon = true) {
//do something
}
It works as expected with default values. But when I want to change the value of one variable it doesn’t work:
my_function($icon = false); // this doesn't change anything
I have to call it with all variables to make changes take effect:
my_function($text = '', $relative = false, $icon = false); // this changes the output
I am working in php 5.4.1 and WordPress. What I do wrong? Thanks.
You must provide values for any default arguments to the left (in function signature) of the argument you want to change.
So given the function:
Here are some examples:
You can’t do that in PHP. Well, you can, but it doesn’t do what you think it does. What this does is:
$icon
tofalse
false
as the 1st parameter tomy_function
If you want to change the third parameter, you need to also pass the first two.
Note: I think it’s python that lets you call functions like that, to set only the Xth parameter.
Nothing wrong, that’s how PHP works.
And when you’re calling a function, you shouldn’t put variables in the parameter list as you might get undesired results as the variables will be assigned those values. So, this is fine:
or:
or anything in between, no need to assign values.
You may use below code:
WARNING: if you use this way. you should initialise the variable or check the if it is exists.