PHP - Inherit function default value
I have a function that look like this:
function test($arg1 = 'my_value', $arg2 = 'second')
{
}
When I call it I only want to set the second value to something different, like this:
test(inherit, 'changed value');
I found out that it is possible to开发者_开发百科 add this line to my function (when my "inherit" is changed to null):
$arg1 = ( is_null( $arg1 ) ? 'my_value' : $arg1 );
Is there a better way, a nicer way to solve it?
Depending on the nature and number of your parameters it may be reasonable to use named parameters (at least emulated):
function xyz($args) {
$args += array(
'x' => 'default',
'q' => 'default 2',
// ...
);
// ...
}
xyz(array('q' => 'hehe, not default'));
The way you have solved it is actually pretty usable.
The other way is to pass the same value as the default value every time on the function call.
If that is structural, then you have to reconsider the function.
Make two different functions:
// Full function
function testex($arg1 = 'my_value', $arg2 = 'second')
{
}
// Shorthand when just argument 2 is needed
function test2($arg2 = 'second')
{
return testex('my_value', $arg2);
}
That way, you don't have to pass null to the first parameter when you don't need to.
You will have to flip them, you can't leave the first value to be blank,
Set the first value and let the second one be the default value;
UPDATE:
If you want to have dynamic length to your argument consider using the func_get_args();
function something() {
$args = func_get_args();
....
}
then you can test your arguments for different value or datatype to make them do whatever yuo please
精彩评论