PHP 8 create_function Replacement

PHP 8 create_function Replacement

If you’re a PHP developer, you may have used create_function in the past to create anonymous functions. However, with the release of PHP 7.2, this function has been marked as deprecated. And with PHP 8, create_function is now highly discouraged, as it poses potential security risks.

So, what should you use instead of create_function? There are several alternatives that you can choose from, and each has its own advantages.

Closures: Closures are anonymous functions that can be assigned to variables or passed as arguments to other functions. They are more flexible than create_function and provide greater control over variables and scope.

Here’s an example of using closures instead of create_function:

$myFunc = function ($arg1, $arg2) {
  return $arg1 + $arg2;
};
echo $myFunc(2, 3); // outputs 5

Anonymous Classes: Anonymous classes are classes that can be defined without a name. They are similar to closures in that they provide greater control over variables and scope.

Here’s an example of using anonymous classes instead of create_function:

$myClass = new class {
  public function add($arg1, $arg2) {
    return $arg1 + $arg2;
  }
};
echo $myClass->add(2, 3); // outputs 5

Named Functions: Named functions are regular functions that can be defined with a name. They are easier to read and understand than anonymous functions, and they can be reused throughout your code.

Here’s an example of using named functions instead of create_function:

function myFunc($arg1, $arg2) {
  return $arg1 + $arg2;
}
echo myFunc(2, 3); // outputs 5

In addition, if you really need to use create_function, there is a replacement function that you can use in PHP 8. This function is designed to mimic the behavior of the original create_function, but with better security and performance. Here’s how to use it:

/**
 * This is a PHP 8 replacement function for the deprecated create_function function that allows developers to create anonymous functions at runtime using a string of PHP code as input.
 *
 * @param string $arg The argument list for the anonymous function.
 * @param string $body The body of the anonymous function.
 * @return callable Returns a new anonymous function.
 */
if ( ! function_exists( "create_function" ) ) {
    function create_function( $arg, $body ) {
        static $cache          = []; // A static array used to store previously created functions.
        static $max_cache_size = 64; // The maximum size of the cache.
        static $sorter; // A callback function used to sort the cache by hit count.

        if ( $sorter === null ) {
            // Define the sorter callback function.
            $sorter = function ( $a, $b ) {
                if ( $a->hits == $b->hits ) {
                    return 0;
                }
                return $a->hits < $b->hits ? 1 : -1;
            };
        }

        // Generate a unique key for the current function.
        $crc = crc32( $arg . "\\x00" . $body );
        if ( isset( $cache[$crc] ) ) {
            // If the function has already been created and cached, increment the hit count and return the cached function.
            ++$cache[$crc][1];
            return $cache[$crc][0];
        }

        if ( sizeof( $cache ) >= $max_cache_size ) {
            // If the cache size limit is reached, sort the cache by hit count and remove the least-used function.
            uasort( $cache, $sorter );
            array_pop( $cache );
        }

        // Create a new anonymous function using `eval` and store it in the cache along with a hit count of 0.
        $cache[$crc] = [
            ( $cb = eval( "return function(" . $arg . "){" . $body . "};" ) ),
            0,
        ];
        return $cb;
    }
}

To use this function, you can simply call it with two parameters: the argument list for the anonymous function, and the body of the anonymous function. The function will then create a new anonymous function using eval and store it in a cache for future use.

However, keep in mind that even though this replacement function is more secure than the original create_function, it’s still not recommended to use it in production code. Instead, consider using one of the alternatives we mentioned earlier, such as closures, anonymous classes, or named functions. These alternatives are safer, more efficient, and more in line with modern PHP development standards.


Stay in the loop with our web development newsletter - no spam, just juicy updates! Join us now. Join our web development newsletter to stay updated on the latest industry news, trends, and tips. No spam, just juicy updates delivered straight to your inbox. Don't miss out - sign up now!


We’ve tried our best to explain everything thoroughly, even though there’s so much information out there. If you found our writing helpful, we’d really appreciate it if you could buy us a coffee as a token of support.

Also, if you’re interested in learning more about WordPress, Javascript, HTML, CSS, and programming in general, you can subscribe to our MailChimp for some extra insights.

1 thought on “PHP 8 create_function Replacement”

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.