If you have a wordpress plugin, more than likely you are using add_action and/or add_filter. No problem, until you get this error:
1 |
Warning: call_user_func_array() expects parameter 1 to be a valid callback, cannot access self:: when no class scope is active in /home/wpcom/public_html/wp-includes/plugin.php on line ......... |
One of the annoyances of wordpress is that tracking bugs when in actions or filters can be a bit of a hassle, but you don’t know where the error actually originated, but with a bit of grep-ing of searching you can find the issue. With the error above however, what’s going on is not so evident. Consider the following plugin that does nothing:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
final class doNothing { static $emptyString = ''; static function init() { add_action( 'wp_footer', array( self, 'output' ) ); } static function output() { // Don't echo anything echo self::$emptyString; } } doNothing::init(); |
Nothing seems wrong here, however, it throws the warning above. The right way of doing this is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
final class doNothing { static $emptyString = ''; static function init() { add_action( 'wp_footer', array( __CLASS__, 'output' ) ); } static function output() { // Don't echo anything echo self::$emptyString; } } doNothing::init(); |
The key being __CLASS__ instead of self on the add_action line. When using static classes add_action and add_filter don’t like self however, if your class is not static, therefore, instantiated you can use add_action( $this, 'function' ) no problem. Seems odd, but that’s how it is.