Skip to content

Instantly share code, notes, and snippets.

@RiFi2k
Last active April 10, 2017 02:30
Show Gist options
  • Save RiFi2k/72ff587be843fe5a7d99d39d99672fc0 to your computer and use it in GitHub Desktop.
Save RiFi2k/72ff587be843fe5a7d99d39d99672fc0 to your computer and use it in GitHub Desktop.
// 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.
// So add a method to provide the class instance:
final class My_Plugin
{
private $var = 'foo';
public function __construct()
{
add_filter( 'get_my_plugin_instance', [ $this, 'get_instance' ] );
}
public function get_instance()
{
return $this; // return the object
}
public function foo()
{
return $this->var; // never echo or print in a shortcode!
}
}
add_shortcode( 'baztag', [ new My_Plugin, 'foo' ] );
// Now, when someone wants to get the object instance, s/he just has to write:
$shortcode_handler = apply_filters( 'get_my_plugin_instance', NULL );
if ( is_a( $shortcode_handler, 'My_Plugin ' ) )
{
// do something with that instance.
}
// Old 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' ) );
// this is the way, but i would suggest to write a getter and setter for that variable.
class Testclass
{
private $testvar = "default value";
public function setTestvar($testvar) {
$this->testvar = $testvar;
}
public function getTestvar() {
return $this->testvar;
}
function dosomething()
{
echo $this->getTestvar();
}
}
$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment