Question

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.

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top