0

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?

4
  • 3
    PHP function docs: default argument values Commented Mar 6, 2012 at 14:26
  • possible duplicate of PHP function with unlimited number of parameters Commented Mar 6, 2012 at 14:30
  • @Shiplu I disagree. That question is a bit different, and it makes no reference to default argument values. Commented Mar 6, 2012 at 14:34
  • thanks all, shame I can't accept more than one answer :( Commented Mar 6, 2012 at 14:41

4 Answers 4

2
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.
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, you can assign a default value to a param in PHP. You can overwrite it using my_func("None Empty String") for example!

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.