Often I write functions whose operation depends depends on the type of some argument. An example would be a function that would help me to insert rows into a mysql database.
function insert($table, $columns, $values) {
if(is_string($values)) {
$values = "('" . $values . "')";
}
else if(is_array($values)) {
$values = "('" . implode("','", $values) . "')";
}
//process $table and $columns here
mysql_query("INSERT INTO $table $columns $values");
}
The idea is that sometimes I will only want to insert a single value but sometimes I will want to insert an array of values. However, this means that the type of $values will depend on the situation and I notice that in general, the built-in PHP functions tend to avoid this. I feel like if the PHP core implemented such a function, it would instead be split into insertString and insertArray to handle both cases. The benefits of overloading the type are that the user doesn't need to worry about what they put into $values as long as it is a string or an array. For example, if they forget that they can pass in a string, they can still pass in array('singleValue')
without any problems. Therefore, the using the function becomes easier. Are there any pitfalls with this approach?
Furthermore, we could extend our function to insert multiple rows at once. These would be input as a multidimensional array and so would need a line that processed them as follows:
if(is_multi($values)) {
foreach($values as $key => $value) {
$values[$key] = "('" . implode("','", $value) . "')";
}
$values = implode(",", $values);
}
Again we could either tack this on to the original function or create a new function, insertMulti. The difference between this case and the earlier case is that technically the type of $values doesn't change between insertArray and insertMulti. However, the way in which we handle $values does change and this change is dependent on the structure of $values. So if there are benefits and pitfalls to type overloading, do they apply to this situation as well or should this be treated differently?
Edit: Thank you for your answers! I realise that there are many PHP functions that accept mixed values but there are also many that do not. For example, strlen
and count
seem to me to be analogous functions except that one handles strings and the other handles arrays and objects. Would it be better then to implement countAll
which handles strings, arrays and objects? Are they only kept separate for historical reasons?