0

I have a few filters that I want to apply based on parameters set by, and in, a larger class.

The way I'm currently doing it is with something that looks like this:

public static function setCustomFilter($name){
    self::$name = $name;
    add_filter('event', function ($args) {
        //$name; // wrong scope
        CustomClass::$name; 
    });
}

In order to access $name inside of the filter function I'm setting it to a static field variable on the class. Otherwise $name will be undefined inside of the filter function.

This seems very clumsy. Are there ways of doing this more elegantly without global or field variables?

Fluxian
  • 575
  • 1
  • 4
  • 12
  • 2
    You can use the `use` keyword to pass additional variables into the callback function - https://www.php.net/manual/en/functions.anonymous.php, https://stackoverflow.com/q/1065188/1427878 – CBroe Aug 01 '22 at 11:58
  • @CBroe ah! Never heard of this. What's the method header supposed to be like if your function is defined inside of a class? public static function setCustomFilter($name) use ($name){} is reporting a syntax error. The examples use something like $setCustomFilter = function() use (){} – Fluxian Aug 01 '22 at 12:05
  • No, that part you need to keep as it is, passing in $name as a normal parameter. The `use` comes into play in the place where you have the anonymous function, that you are passing to add_filter as callback - `add_filter('event', function ($args) use ($name) {...} );` – CBroe Aug 01 '22 at 12:07
  • Ah, now I get that. That's very clean thank you :) – Fluxian Aug 01 '22 at 12:09

0 Answers0