I have a custom class which I use for several cases extending it, for example
class A {
public function show_things() {
print_r( apply_filter( 'yet_another_filter', array( 'coffee', 'tea' ) ) );
}
}
class B extends A {
public function __construct() {
parent::__construct();
add_filter( 'yet_another_filter', array( $this, 'other_things' ) );
}
public function other_things( $things ) {
return array( 'crisps', 'beer' );
}
}
class C extends A {
public function __construct() {
parent::__construct();
// no filter added here
}
}
Now, I create instances of Class B and C:
$b = new B;
$c = new C;
When displaying the things of $b
, with
$b->show_things(); // gives crisps, beer
When displaying the things of instance $c
where I did not add any filter, I get the same, since the filter added by instance $b
is ‘global’:
$c->show_things(); // gives crisps, beer, which is logical
But I would like to get the coffee and tea, since I did not add the filter inside class C. Do I have to add the instance itself when adding the filter and then checking for $this
? Or is there another (better) approach?