PHP 8 create_function Replacement

PHP 7.2 deprecated create_function then PHP 8 highly discourage the use of create_function, below are the code replacement in case you need it back:

/* 
 * PHP 8 create_function replacement.
 */
if ( ! function_exists( "create_function" ) ) { 
	function create_function( $arg, $body ) { 
		static $cache = array(); 
		static $max_cache_size = 64;
		static $sorter;
		
		if ( $sorter === NULL ) {
			$sorter = function( $a, $b ) {
				if ( $a->hits == $b->hits ) {
					return 0;
				}
		
				return ($a->hits < $b->hits) ? 1 : -1;
			};
		}
		
		$crc = crc32($arg . "\\x00" . $body);
		
		if (isset($cache[$crc])) {
			++$cache[$crc][1];
			return $cache[$crc][0];
		}
		
		if ( sizeof($cache) >= $max_cache_size ) {
			uasort($cache, $sorter);
			array_pop($cache);
		}
		
		$cache[$crc] = array( $cb = eval('return function('.$arg.'){'.$body.'};'), 0 );
		return $cb; 
	} 
}

Comment

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