In PHP, which is dynamically typed, we can create functions that may accept multiple data types as parameters. We can then operate on the data depending on the type of the variable. There are two ways to do this:
Approach One:
function doSomething1($param) {
$type = gettype($param);
if ($type === 'string') {
// do something
}
else if ($type === 'integer') {
// do something
}
else if ($type === 'array') {
// do something
}
}
Approach Two:
function doSomething2($param) {
if (is_string($param)) {
// do something
}
else if (is_int($param)) {
// do something
}
else if (is_array($param)) {
// do something
}
}
As far as I know, these two approaches are functionally equivalent from a testing perspective, but since PHP has so many gotchas, I gotta ask if there is anything I could miss if I favour one approach over the other?
From a performance perspective, is it right to say approach one is faster than two because PHP function calls are expensive? Or is
gettype()
a much more expensive operation than the individualis_*()
functions?Is there any coding idioms / style guides regarding this?
Update
From my benchmark using PHP 7.0.4, a million iterations of doSomething2()
took 159ms, slightly less than half the time of doSomething1()
at 315ms. This was regardless of whether a string (first check) or array (last check) was passed in. This seems to suggest that gettype()
is indeed an expensive operation, and more expensive than multiple function calls using is_*()
.
Anyone with more insight into why this might be, your help is appreciated.
is_*
is expectedly slower than 159ms forgettype
. – Deportation