Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Currently i am using the following generic flow for adding the shortcode for a plugin.

class MyPlugin {

    private $myvar;

    function baztag_func() {
        print $this->myvar;            
    }
}

add_shortcode( 'baztag', array('MyPlugin', 'baztag_func') );

Now when this class and it's method are called i get the following error.

Fatal error: Using $this when not in object context in ...

(Line no is where i have printed the $this->myvar)

Is this a problem on Wordpress's end or is there is something i'm doing wrong? It seems to be something really simple.

share|improve this question
    
off topic - make the function static. –  kaiser Sep 27 '12 at 15:21

2 Answers 2

up vote 10 down vote accepted

As the error says you need an instance of the class to use $this. There are at least three possibilities:

Make everything static

class My_Plugin
{
    private static $var = 'foo';

    static function foo()
    {
        return self::$var; // never echo or print in a shortcode!
    }
}
add_shortcode( 'baztag', array( 'My_Plugin', 'foo' ) );

But that’s not real OOP anymore, just namespacing.

Create a real object first

class My_Plugin
{
    private $var = 'foo';

    public function foo()
    {
        return $this->var; // never echo or print in a shortcode!
    }
}

$My_Plugin = new My_Plugin;

add_shortcode( 'baztag', array( $My_Plugin, 'foo' ) );

This … works. But you run into some obscure problems if anyone wants to replace the shortcode.

Better solution: create the object in your class

class My_Plugin
{
    private $var = 'foo';

    protected static $instance = NULL;

    public static function get_instance()
    {
        // create an object
        NULL === self::$instance and self::$instance = new self;

        return self::$instance; // return the object
    }

    public function foo()
    {
        return $this->var; // never echo or print in a shortcode!
    }
}

add_shortcode( 'baztag', array( My_Plugin::get_instance(), 'foo' ) );
share|improve this answer
    
thanx man ... thats priceless info since wordpress.org did not tell this much on their add_shortcode documentation page. I had figured out the solution but since you have ruled that out as a bad practice and you have a better solution so i mark this problem as solved:) –  hussain Aug 10 '12 at 7:49

Make sure that you make an instance of your class before using it unless you are sure it's supposed to be called statically. When you call a method statically, you don't use any instances and therefore it doesn't have access to any member variables or methods.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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