Answers:
如错误所示,您需要使用该类的实例$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' ) );
这...有效。但是,如果有人想替换短代码,就会遇到一些晦涩的问题。
因此,添加一个方法来提供类实例:
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' ) );
NULL === self::$instance and self::$instance = new self;
?我有点困惑,因为===
和and
被使用了,但是if
如果您不明白我的意思,那就不用了。
class stockData{
function __construct() {
add_shortcode( 'your_shortcode_name', array( $this, 'showData' ) );
//add_action('login_enqueue_scripts', array( $this,'my_admin_head'));
}
function showData(){
return '<h1>My shortcode content</h1>' ;
}
}
$object=new stockData();
class my_PluginClass {
public function __construct( $Object ) {
$test = add_shortcode( 'your_shortcode_name', array( $Object, 'your_method_name' ) );
}
}
class CustomHandlerClass{
public function your_method_name( $atts, $content ) {
return '<h1>My shortcode content</h1>' ;
}
}
$Customobject = new CustomHandlerClass();
$Plugin = new my_PluginClass( $Customobject );
static
。