WordPress.org

Ready to get started?Download WordPress

Forums

OOP, Shortcode Function and Property Types (6 posts)

  1. toneburst
    Member
    Posted 1 year ago #

    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

  2. Chris
    Member
    Posted 1 year ago #

    Try using &$this instead of __CLASS__

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

    __CLASS__ only refers to the class name not the instance.

  3. toneburst
    Member
    Posted 1 year ago #

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

    Thanks again,

    a|x

  4. toneburst
    Member
    Posted 1 year ago #

    That does it- thanks, Chris!

    a|x

  5. Chris
    Member
    Posted 1 year ago #

    You're welcome, a|x :) Glad I could help

  6. Barry
    Member
    Posted 1 year ago #

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

    array($this, 'shortcode')

Topic Closed

This topic has been closed to new replies.

About this Topic