PHP5, Inheritance, Singleton – action & filter hook limitations

You don’t have to declare the constructor public, just the action hook function.

Example:

<?php
/*
Plugin Name: Singleton Action
*/

class Singleton_Demo
{
    /**
     * @static $instance Objekt
     * @access private;
     */
    private static $_instance   = NULL;

    protected function __construct() {}
    private final function __clone() {}

    public static function getInstance()
    {
        if ( self::$_instance === NULL )
        {
            self::$_instance = new self;
        }

        return self::$_instance;
    }

    public function hook_test()
    {
        print '<p>Works!</p>';
    }
}

add_action( 'wp_footer', array ( Singleton_Demo::getInstance(), 'hook_test' ) );

Anyway, I wouldn’t use a Singleton. 🙂

Leave a Comment