PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I want to make a php function suitable for both scalar and array input like this, which gives the (latest) modification time of one or more files. So return value in both cases is only one integer, but the argument of the function can be a single file name, or a array of file names. It works, but I'm not convinced it is allowed. As far as I know functions are compiled only once, and with strongly typed languages you cannot change the type of arguments after compilation. Anyone has a thought?
Knit picking here.. but I would expect if I passed an array of something, to get an array back of each individual element processed. Instead you only return the one with the highest value.
If you ask me - I wouldn't. I'm pretty comfortable with functions accepting different (but cohesive) types of input arguments which are finally casted to a specific one.
function getLatestFileModificationTime($files)
{
if (is_string ($files))
return getLatestFileModificationTime(array($files));
$latestModificationTimes = array();
foreach ($files as $file)
$latestModificationTimes[] = filemtime($file);
return max($latestModificationTimes);
}
is closer to what I would do. Probably because I'm used to use overloading of functions (C++ style) and it's very often used in JavaScript frameworks as ExtJS . So, the general pattern is:
function func(mixed $arg)
{
if (is_some_type_1($arg))
return func(type_1_cast($arg));
if (is_some_type_2($arg))
return func(type_2_cast($arg));
...
if (is_some_type_N-1($arg))
return func(type_N-1_cast($arg));
if (is_some_type_N($arg))
return func(type_N_cast($arg));
// main_implementation_for_type_0_goes_here
}
There are 10 types of people in this world, those who understand binary and those who don't
switch (true) {
case is_string($files): $files = array($files); break;
case $files instanceof Traversable: $files = iterator_to_array($files); break;
default: // omitted
}
if (!is_array($files)) throw new InvalidArgumentException('$files should be either a string, something traversable or an array');
// work uniformly with $files as array