Jump to content

[solved] Can I pass a variable to a hook function?


Robin S
 Share

Recommended Posts

Is it possible to define a variable in the place that the hook is attached (e.g. ready.php or a template file) and then access that variable inside the hook function?

$animal = 'cat';
$this->addHookAfter('Class::method', function($event) {
    // is there some way to use $animal here?
});

I tried passing the variable as a second argument in the anonymous function but got an error.

Missing argument 2 for ProcessWire\ProcessWire::{closure}()

 

Link to comment
Share on other sites

You can use $this->animal

$this->animal = 'cat';
$this->addHookAfter('Page::render', function($event) {
    bd($this->animal);
});

or you can also do this:

$animal = 'cat';
$this->addHookAfter('Page::render', function($event) use($animal) {
    bd($animal);
});

 

  • Like 7
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...