The Problem
When using hooks, the handler needs to have a public
accessor, which goes against encapsulation rules. That means that the handler can be accessed by clients even when it shouldn't be, potentially causing issues. Of course, it won't make any problems If I won't use this, but still - it breaks the rules that are important to me.
class Widgets
{
public function __construct()
{
add_action('get_sidebar', [$this, 'addLinks']);
}
public function addLinks(): void
{
echo '<ul>...</ul>';
}
}
Solution
Are there any chances to prevent this? The first idea I'm thinking about is using anonymous function when I need to hook private function. There won't be a possibility to unhook the callback, but is this needed when it comes to private methods? 😎
class Widgets
{
public function __construct()
{
add_action('get_sidebar', fn() => $this->addLinks());
}
private function addLinks(): void
{
echo '<ul>...</ul>';
}
}