Getting instance variable in scope of ‘wp_enqueue_scripts’

The best way to solve this is to simplify your code. Right now, ScriptQueuer::QueueCss() is just a static method, and it is getting its data too late.

You could use an immutable object instead and then just register one of its methods as callback.

Example:

class Enqueuer {

    private $stylesheets;

    public function __construct( ArrayObject $stylesheets ) {

        $this->stylesheets = $stylesheets;
    }

    public function enqueue() {

        foreach ( $this->stylesheets as $stylesheet )
            wp_enqueue_script(
                $stylesheet->handle(),
                $stylesheet->url(),
                $stylesheet->dependencies(),
                $stylesheet->version(),
                $stylesheet->in_footer()
            );
    }
}

add_action( 'wp_enqueue_scripts', [
    new Enqueuer( $settings->GetCss() ),
    'enqueue'
] );

No need to pass data to the enqueue method, no need for a closure, and the code is easy to read.

Leave a Comment