• Hi,

    I’m struggling the PHP OOP concepts, trying to make a shortcode plugin.
    Here’s my very simple shortcode class, so far:

    class ell_jt_shortcode {
    	static $defs = NULL;
    	static $addscripts = false;
    
    	function __construct() {
    		///////////////////
    		// Add shortcode //
    		///////////////////
    		add_shortcode( 'ell-jtweets', array( __CLASS__, 'handle_shortcode' ) );
    	}
    	function handle_shortcode( $atts ) {
    		return var_dump(self::$addscripts);
    	}
    }
    $jtshortcode = new ell_jt_shortcode();

    This seems to work OK, but I’m wondering why I only seem to be able to access static variables inside the shortcode functions. From reading OOP tutorials, I was assuming that I could use a private or protected variable for $addscript, like so:

    class ell_jt_shortcode {
    	static $defs = NULL;
    	private $addscripts = false;
    
    	function __construct() {
    		///////////////////
    		// Add shortcode //
    		///////////////////
    		add_shortcode( 'ell-jtweets', array( __CLASS__, 'handle_shortcode' ) );
    	}
    	function handle_shortcode( $atts ) {
    		return var_dump($this->addscripts);
    	}
    }
    $jtshortcode = new ell_jt_shortcode();

    But this produces a fatal “Using $this when not in object context in PHP” error. Is this as expected? Is there some other way I should go about creating a PHP class for my shortcode. Is using a static variable in this context OK? I’m using a static for the default settings, but I think this is OK, as they’re always going to be the same.

    I’m still struggling with basic OOP concepts, I must admit. I’ve been writing procedural PHP for quite a long time, but am trying update myself, finally. It’s quite hard though, as a completely self-taught code-tinkerer.

    a|x

Viewing 5 replies - 1 through 5 (of 5 total)
  • Try using &$this instead of __CLASS__

    add_shortcode( 'ell-jtweets', array( &$this, 'handle_shortcode' ) );

    __CLASS__ only refers to the class name not the instance.

    Thread Starter toneburst

    (@toneburst)

    Ah, thanks Chris. That makes sense. I copies that part from a tutorial where a static class was used.

    Thanks again,

    a|x

    Thread Starter toneburst

    (@toneburst)

    That does it- thanks, Chris!

    a|x

    You’re welcome, a|x ?? Glad I could help

    Barry

    (@barryhughes)

    Just to chip in: I think dropping the ampersand would be preferable, certainly with PHP 5.0 or greater:

    array($this, 'shortcode')

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘OOP, Shortcode Function and Property Types’ is closed to new replies.