5

I have a PHP function signature that looks like this, where I want the 4th param to be NULL by default if nothing is supplied.

testfunction($param1, $param2, $param3, $param4=NULL) {
    //do stuff
}

I can also call using 4 params as such

x = testfunction('100', 'abc', 'xxx', null);

Why is it that I can also call the function using 3 parameters without any errors?

x = testfunction('100', 'abc', 'xxx');

Is what i'm doing even correct (using 3 params)? Any thoughts about how this relates to traditional method overloading where separate function signatures are defined?

My question is general in nature. Hope someone can shed some light on and around it.

2
  • You have not to pass parameters which have a default value. So what you're doing is correct. Commented May 5, 2014 at 9:51
  • because the 4th parameter is optional. you may be interested in this SO question stackoverflow.com/questions/4697705/php-function-overloading Commented May 5, 2014 at 9:52

1 Answer 1

9

When you declare a function like this:

testfunction($param1, $param2, $param3, $param4=NULL) {
    //do stuff
}

You're telling PHP that $param4 already has a value, so when that function is called, a value is already assigned to it. It doesn't expect you to send an argument for that parameter because a default one has already been assigned.

It therefore knows the function will be able to operate (to a certain extent) as it should. It's useful for making optional parameters.

However when you declare a function as this:

testfunction($param1, $param2, $param3, $param4) {
    //do stuff
}

PHP Expects you to send through that argument ($param4), because without it, the function won't be able to accomplish what you've set it out to do, at least so PHP assumes, because you would never create a function with 4 parameters where not one of them are used in the function body.

Make sense?

Sign up to request clarification or add additional context in comments.

1 Comment

in php you can have a function like function test(){} and call it as test('arg1',arg2)`. function signature is just the function name.

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.