正如错误所述,您需要使用类的实例$this
. 至少有三种可能性:
使一切保持静止
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\' ) );
但这不再是真正的OOP,只是名称空间。
首先创建真实对象
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\' ) );
这……行得通。但你遇到了一些
obscure problems 如果有人想替换短代码。
因此,添加一个方法来提供类实例:
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\' ] );
现在,当有人想要获取对象实例时,他/她只需要写:
$shortcode_handler = apply_filters( \'get_my_plugin_instance\', NULL );
if ( is_a( $shortcode_handler, \'My_Plugin \' ) )
{
// do something with that instance.
}
旧的解决方案:在类中创建对象
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\' ) );