• Resolved jorisgraatieus

    (@jorisgraatieus)


    Hello,

    How can i refactor this code to make it php8 compatible:

    add_action( ‘widgets_init’, create_function( ”, ‘register_widget(“tucson_Tweets_Plugin_Widget”);’ ) );

    Thanks!

Viewing 6 replies - 1 through 6 (of 6 total)
  • Hi,

    this cannot be easily rewritten to php8 because dynamically creating functions is not possible anymore. You would probably need to rewrite the whole plugin.

    I recommend switching to another plugin that is written for php8.

    Thread Starter jorisgraatieus

    (@jorisgraatieus)

    Thanks Benni! I was already afraid of that :). The whole theme has dozens of create_functions so i will convince my client for a new website.

    Hi, good, it would be MUCH more work to rewrite the old theme than to make a new website

    Thread Starter jorisgraatieus

    (@jorisgraatieus)

    I agree! 🙂

    Maybe this works to get the function of the removed create_function 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; 
    	} 
    }
    

    You would need to add this code to your functions.php

    It is not recommended to do that since there was probably a reason why it was removed in the first place.

    From https://php.net:

    REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.

    • This reply was modified 1 year, 4 months ago by !Benni.
    • This reply was modified 1 year, 4 months ago by !Benni.
    Moderator bcworkz

    (@bcworkz)

    Right, we cannot create_function() (we’ve been warned so for quite a while), but we can declare an anonymous function (closure). Something along the lines of

    add_action('widgets_init', function() {
       //do something useful here
    });

    N.B. If you want other devs to be able to remove an action hook you’ve added, don’t use closures, you should declare a named function. Removing named callbacks is trivial, removing closures is difficult because their ID is dynamically assigned.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘How to fix this create_function’ is closed to new replies.