0

I want to run a function when my theme is activated. I have to add the theme activation hook within a php class:

final class My_Class_Name {

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new self;               
            self::$instance->actions();
        } else {
            throw new BadFunctionCallException(sprintf('Plugin %s already instantiated', __CLASS__));
        }
        return self::$instance;
    }


   // some code

   add_action('after_switch_theme', array( $this, 'activate' ));

   function activate() {
      // some code
   }

   // more code

}

My_Class_Name::getInstance();

When I activate my theme I get the following php error:

PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'My_Class_Name' does not have a method 'activate' in /Applications/MAMP/htdocs/wp-themes/test/wp-includes/class-wp-hook.php on line 288

If I use add_action('after_switch_theme', 'activate' );

I get

PHP Fatal error: Cannot access self:: when no class scope is active

How can I make the hook work?

2

It looks like you are adding the hook just inside the body of the class. Try adding it into an init() method and calling it after it is instantiated or at the very least in the constructor.

I think the issues is that the hook is being registered before the class has been fully read by PHP?

Try this:

final class My_Class_Name {

    function init() {
        add_action('after_switch_theme', array( $this, 'activate' ));
    }

    function activate() {
    }
}

$class = new My_Class_Name();
$class->init();

Hope this helps!

  • That is much different than the code above? Seems like there is more to this than originally expected – Welcher Mar 26 '18 at 17:34
  • yes there is more.. I updated my code – at least three characters Mar 26 '18 at 19:24
  • This is probably due to trying to call a method that is not static on a static instance. Based on the new error, I think there is still some missing code as it looks like they have a private constructor in the HXTR_Email_Subscription class. – Welcher Mar 27 '18 at 12:52
0

Just do not use "OOP" if you do not intent to treat things as object or extendab;e classes, use proper namespacing instead and save yourself the pointless headache.

Singleton pattern is not OOP and encapsulating global functions in a class brings no structural or any other kind of value, just forcing you to use much more characters to do anything.

The only use I found so far to have a singleton pattern in PHP is to be able to autoload the code, but in that case you do not need to create the object at the place you do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.