I need a little help getting my head around passing instance variable to a hook.

I am reading the CSS files I need in my template dynamically and storing them in a $settings object that I am keeping inside the scope of my plugin namespace.

So I want to do something like this:

add_action( 'wp_enqueue_scripts',function() {
    \mynamespace\ScriptQueuer::QueueCss($settings->GetCss());
} );

but obviously I need to pass the $settings->GetCss() return value into the scope somehow.

Do I make my $settings object global somehow? I am not sure how to do that and also not sure its the best approach. Is there anyway to achieve this or do I have to have all the CSS files hardcoded in a static function?

1
1

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 Reply

Your email address will not be published. Required fields are marked *