0

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?

dotgc
  • 500
  • 1
  • 7
  • 21
  • http://php.net/manual/en/function.function-exists.php – Viktor Koncsek May 30 '16 at 08:12
  • and how do you use it to check if the splat operator exists? – dotgc May 30 '16 at 08:14
  • You can't handle a syntax error, because your code fails on parsing phase, not executing. If you need to support old PHP versions, just use `func_num_args()` and `func_get_args()`. They are still avaiable in newer versions. – Jakub Matczak May 30 '16 at 08:18
  • @dragoste: I know they exist in the newer versions. I wanted to know if anything like this is even possible. – dotgc May 30 '16 at 08:19

1 Answers1

0

If you can use exec or similar functions, try this:

Catching fatal error

Make a simple file with the splat operator, than execute that file and parse the result. You'll probably want to store the result somewhere and only check it on first runtime, or maybe monthly.

Community
  • 1
  • 1
Viktor Koncsek
  • 564
  • 3
  • 13