Attach a private function at a hook?

I have a class with some private public functions. The thing is that I don't want some of the functions to be able to be called outsite of the class, so I want to make them private. But I need to hook them at particular hooks and the hooks cannot call them if they are private. Is there some workaround for that?

Topic private functions Wordpress

Category Web


As of PHP 5.4 or higher, you can achieve this using a closure and bindTo() method:

$cb = function(){
  $this->callPrivateMethod();
};

$cb->bindTo($this);

add_action('init', $cb);

The above code is executed in the scope of a class hence $this is a valid value.


Generally hook performs outside of a class. It has been invoked inside a class or class method. So you cannot use it in a hook. If you do it by forcefully you shall have to instantiate inside a public method first, then use the public method into any hook. Example:

<?php
class tlSmAdminMenu{
    public function __construct(){
        add_action('admin_menu', array( $this, 'add_menu_page'));
    }
    public function add_menu_page(){
        add_menu_page('Themelines Plugin', 'TL Social Monster', 'manage_options', 'tl_social_monster', array( $this, 'admin_menu_cb'), '
dashicons-networking', 110);
    }
    public function admin_menu_cb(){
        $this->doStaff();
    }
    private function doStaff(){
        echo "<center><h1>THEMELINES SOCIAL MONSTER</h1></center>";
    }
}
if(class_exists('tlSmAdminMenu')){
    $tl_sm_obj= new tlSmAdminMenu();
}
?>

No that's impossible. When WordPress calls a method it has to be public. You could write a public method that is called on the hook which calls a private method inside.
Not sure if that makes sense though …


Here is an example;

add_action( 'template_redirect', array( 'someClass', 'init' ));

class someClass {

    protected static $content = 'oh yeah, private!';    

    public static function init() {
        $class = __CLASS__;
        new $class;
    }

    private function __construct() {
        add_filter('the_content', array(&$this, 'get_this_function'));
    }

    public static function get_this_function(){
         return self::my_funk_she_on();
    }

    private static function my_funk_she_on(){
        return self::$content;
    }

}

In this example I am filtering the_content by passing a private function which gets its value from a private variable. Now since you can't call this directly my get_this_function is what will return what's private and that's what I pass into my constructor that adds the appropriate filter upon template_redirect.

You don't need to use static methods by the way, some recommend against it, but do as you please.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.