Search code examples
phppolyfills

PHP function is not available in my current PHP Version


I would like to use the function array_key_first (PHP 7 >= 7.3.0).

My current PHP Version is 7.2

I use the "Polyfill" as described within the "User Contributed Notes" section of corresponding PHP manual

If I call the array_key_first function in my index.php which is where the polyfill is, everything works fine.

If I call the array_key_first function within a PHP self-written class, it doesn't work.

How can I define "Polyfills" so that they are "globally" available?

I don't want to define a class method an call it with $this->array_key_first...

I include the following code in my index.php file

    if (!function_exists('array_key_first')) {
        function array_key_first(array $array){
            if (count($array)) {
                reset($array);
                return key($array);
            }
            return null;
        }
    }

Thanks for hints


Solution

  • If you aren't using a composer-based workflow for including files (which can include files automatically when you first require the autoload.php file), there will only be two ways.

    1. Include a file manually to define the function wherever it is used
    2. change the php.ini file to 'prepend' a file (include a PHP file before the main script runs)

      auto_prepend_file="/path/to/polyfill.php"

    If you are on shared hosting, it is unlikely you will be able to change the php.ini file though.

    The polyfill defines the function like this:

     function array_key_first(array $array) { foreach ($array as $key => $value) { return $key; } }