I'm writing a PHP function. I want to be able to do the following;
If the splat operator(...
) is available (i.e PHP version = 5.6+), I want to define the function using that, else I want to define the same function using func_num_args()
and func_get_args()
.
Here' what I tried:
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}
function _insert_keywords_helper($text, $keywords_array) {
$text_words_array = explode(" ", $text);
$idx = 1;
foreach ($keywords_array as $keyword) {
array_splice($text_words_array, $idx * 50, 0, $keyword);
}
return implode(" ", $text_words_array);
}
if (PHP_VERSION_ID < 56000) {
// ... splat operator is not available
function insert_keywords() {
$numargs = func_num_args();
if ($numargs < 2) {
echo "Usage: insert_keywords($text, ...keywords)";
exit();
}
$arg_list = func_get_args();
$text = $arg_list[0];
$keywords = array_slice($arg_list, 1);
return _insert_keywords_helper($text, $keywords);
}
} else {
function insert_keywords($text, ...$keywords) {
return _insert_keywords_helper($text, $keywords);
}
}
It throws a Parse error in PHP version < 5.6. A parse error is a fatal error, so I can't wrap it in a try-catch.
The reason I want to do this is to enable the function to be used independently of the PHP version. I'm not very familiar with the PHP world. So maybe I'm making a few assumption as I write this code.
Any hints?