Reputation: 17711
I have this situation: function a
(a class method, but it's not important, here...) invokes function b
.
Function a
has one parameter (say, $p2
), with a default value.
Function b
has one parameter (say, $q2
), with a default value, too.
If function a
is called without the parameter $p2
, function b
should be called without the parameter $q2
, too, to force it using it's default value.
If function a
is called with the parameter $p2
, function b
should be called with the parameter $q2
.
To clearify with an example:
function a($p1, $p2 = "default value one") {
if ($p2 === "default value") {
b($p1);
} else {
b($p1, $p2);
}
}
function b(q1, q2 = "default value two") {
...
}
Of course it's possible to use a test, as in the example above, but it looks me a really ugly solution... The question is:
Is there a better (faster, cleaner, smarter) code to implement this use case?
Upvotes: 0
Views: 77
Reputation: 43481
Function a
default parameter must have same value as function b
default parameter:
function a($p1, $p2 = null) {
b($p1, $p2);
}
function b($p1, $p2 = null) {
var_dump($p1, $p2);
}
So calling a
with both parameters will pass these parameters to function b
, while calling function a
with only first parameter set will call b
with passed first from user and second parameter as default value:
a(2, 5); // --> (int)2 (int)5
a(2); // --> (int)2 NULL
[UPDATE]
If functions can have different default values, than you need to detect default value:
function a($p1, $p2 = null) {
$p2 = !is_null($p2) ? $p2 : 'defaultB';
b($p1, $p2); // For string use `stricmp($p2, 'defaultA') !== 0`
}
function b($p1, $p2 = 'defaultB');
Upvotes: 0
Reputation: 59681
I think something like this should be what you're looking for:
Just get all function arguments with func_get_args()
, then simply call your next function with call_user_func_array()
.
function a($p1, $p2 = "default value") {
call_user_func_array("b", func_get_args());
}
Upvotes: 1