PHP uses a private method as a callback

I am experimenting with PHP + WP for the first time. I intend to use WP plugin hooks. As a C ++ programmer, I also intend to put all my code in classes. Currently, I’m kind of stuck with the following snippet that should install the WP plugin:

   class SettingsHandler
   {
      public function __construct()
      {
         add_filter('plugin_action_links', array($this, 'AddSettingsLink'), 10, 2);
      }

      private function AddSettingsLink($links, $file)
      {
         if ($file==plugin_basename(__FILE__))
         {
            $settings_link = '<a href="options-general.php?page=options_page">Settings</a>';
            array_unshift($links, $settings_link);
         }       
         return $links;
      }
   }

   $settingsHandler = new SettingsHandler();

This gives me the error message: Warning: call_user_func_array () expects parameter 1 is a valid callback, cannot access the private method SettingsHandler :: AddSettingsLink () in E: \ xampp \ apps \ wordpress \ htdocs \ wp-includes \ plugin.php on line 199

, . , PHP/WP. , , . ?

, :

   class a
   {
      public function __construct()
      {
         $str = " test test ";
         $result = preg_replace_callback('/test/', array($this, 'callback'), $str);
         echo $result;
      } 

      private function callback($m)
      {
         return 'replaced';
      }
   }

   $a = new a();

? ?

+4
1

, preg_match_all .

add_filter $wp_filter. , . , , .

,

public function __construct()
{
    add_filter(
        'plugin_action_links',
        function($links, $file) {
            return $this->AddSettingsLink($links, $file);
        },
        10,
        2
    );
}

, , PHP 5.4 (. ) - $this .

- SettingsHandler __invoke, Functor, .

public function __invoke($links, $file)
{
    return $this->AddSettingsLink($links, $file);
}

ctor

add_filter('plugin_action_links', $this, 10, 2);

__invoke , . , .

, . ctor (, , WP , ). , , .

// your-plugin.php
include 'SettingsHandler.php';
add_filter('plugin_action_links', new SettingsHandler, 10, 2);

.

¹ :, -, Wordpress, - . , .

+3

Source: https://habr.com/ru/post/1531938/


All Articles