Reputation: 21
I notice that in some PHP built in functions such as str_replace there are optional input variables. Can I have have optional input variables in my own functions? If so, how?
Thanks, Brian
Upvotes: 2
Views: 355
Reputation: 180023
An additional option that allows arbitrary ordering of arguments:
function my_function($arguments) {
if($arguments['argument1']) {
// do something
}
if($arguments['argument2'] == 'LOLCAT') {
// do something else
}
}
my_function(array('argument1' => 1, 'argument2' => 'LOLCAT'));
Upvotes: 0
Reputation: 490333
Another alternative you can do is this...
EDIT
somewhat useful function now..
function getLongestString() {
$strings = func_get_args();
$longestString = '';
foreach($strings as $string) {
if (strlen($longestString) < strlen($string)) {
$longestString = (string) $string;
}
}
return $longestString;
}
Which you could then use like this
echo getLongestString('hello', 'awesome'); // awesome
Whilst this may not have been what exactly you were wanting, it is still good to know and solves the question of optional function inputs.
Upvotes: 1
Reputation: 625127
The first way is to use default values for some arguments:
function doStuff($required, $optional = '', $optional2 = '') {
...
}
Now you just include a default value and then someone can do:
doStuff('foo');
doStuff('foo', 1);
doStuff('foo', 2, 3);
You need to choose an appropriate default value if the field isn't specified or to indicate that no value was set. Typical examples are ''
, 0
, false
, null
or array()
.
Or you don't need to specify them at all with func_get_args()
:
function doStuff() {
print_r(func_get_args());
}
func_get_args()
can be used with explicit arguments (the first example) as well.
Upvotes: 8