Reuse variable in hook callback

If you want to use a variable from a another context in a function, create a class:

class CustomLog
{
    private $debug_msg = "";

    public function __construct( $msg )
    {
        $this->debug_msg = $msg;
    }

    public function log()
    {
        error_log( $this->debug_msg, 0 );
    }
}

add_action( 'init', [ new CustomLog( "Hi there!" ), 'log' ], 20 );

Now you can reuse the class multiple times for different messages and hooks.

Leave a Comment