I saw some PHP today I don't understand, can anyone explain it to me?
function my_func($param='')
{
if (empty($param))
{
return false;
}
else
{
return true;
}
}
What I don't understand is the $param variable being assigned an empty string but somehow not being empty inside the function? Is this just a default value?
my_func("string") //makes $param "string"
my_func() //picks default making $param ''
You can have required and optional params like
function my_func($param1, $param2='default')
You can NOT put optional params behind required params
function my_func($param1='', $param2) //gives errors.
Yes, you can assign a default value to a param in PHP. You can overwrite it using my_func("None Empty String") for example!
Your assumption was correct; this allows the developer to assign a default value to the parameter.
If the calling code does not pass a parameter value, the function returns false. Otherwise, $param
is non-empty, and the function returns true.
A potential pitfall with this code is the case of a parameter being passed with an empty value (0, null, etc). The code will return false
even though a parameter was passed.
Yes, the variable inside the parenthesis of the function declaration is a default value, and is used so you can call the function like this:
echo my_func();
Without needing to actually pass a variable to the function at all.