• I’ve created a custom class for a new plugin, instantiated it, and have no trouble using it in or out of functions.

    However, when I try to access a method of the instance within a function called by register_activation_hook(), I receive a PHP “Call to a member function on a non-object” error.

    Yes, I am declaring the instance as a global within the function.

    For example:

    class myClass{
       public function doStuff(){ return true; }
    }
    $myInstance = new myClass();
    register_activation_hook(__FILE__,'do_things');
    function doThings(){
       global $myInstance;
       $test = $myInstance->doStuff(); //non-object error
    }

    The above code SHOULD be valid, but returns a non-object error for doStuff when it’s function is run by register_activation_hook.

    Ideas?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Dutch van Andel

    (@veraxus)

    To answer my own question, I didn’t realize that you could use ANY PHP callback style. On a whim, I simply changed my register_activation_hook to:

    register_activation_hook(__FILE__, $fpdb->install() );

    Bingo. It works.

    Thread Starter Dutch van Andel

    (@veraxus)

    One quick note for anyone stumbling on this, the above “fix” has scope resolution problems with WordPress.

    IMPORTANT NOTES:
    1. Only pass STATIC functions to hook callbacks (fixes scope problem) using the scope-resolution operator (::).
    2. Use only string-formatted callbacks (fixes WP ‘expected callback’ problem).

    The following is the only way to do this without running into problems (note that install() also had to be changed to a static function):

    register_activation_hook(__FILE__, 'myClass::install' );
    Thread Starter Dutch van Andel

    (@veraxus)

    Best Solution:

    Use array-formatted callbacks. For maximum compatibility, the above string-formatted static-method example should be converted to an array-formatted callback like this:

    register_activation_hook(__FILE__, array( 'myClass','install' );

    Here’s why:
    String-formatted static-method callbacks are only supported in PHP 5.2+. To ensure maximum compatibility with earlier versions of PHP (I know, ugh), you should simply use array-formatted callbacks.

    The first array value is the class, the second is the method.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Class gives non-object error when used in register_activation_hook’ is closed to new replies.