From C # I'm used to overloading my methods with variable parameters. Since you cannot do this in PHP , I often create methods like the example below that takes a variable, then I check the type and act accordingly:
showLength('one');
showLength(array(
'one',
'two',
'three'
));
function showLength($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
}
foreach ($arr as $str) {
echo strlen($str).'<br/>';
}
}
output:
3
3
3
5
4
This gives me the same functionality as in C #, but it seems a bit messy, as if there was a better way.
Is this an acceptable way to overload methods in PHP (5.3) or is there a better way?
source
share