用于创建快捷代码的PHP Helper类

时间:2016-07-26 作者:jamie

我创建了一个助手类来扩展其他短代码类。

当我尝试使用$thisadd_shortcode() 函数我收到此错误:

Using $this when not in object context
我如何解决这个问题?

Code below:

父类

//shortcode-helper.php
abstract class ShortcodeHelper {

    private $post_name_id;
    private $short_code_name;

    /**
     * ShortcodeHelper constructor.
     *
     * @param $post_name_id
     * @param $short_code_name
     */
    protected function __construct( $post_name_id, $short_code_name ) {
        $this->post_name_id      = $post_name_id;
        $this->short_code_name   = $short_code_name;
    }

    /**
     * Sets shortcode for the ShortcodeHelper
     */
    public function register() {
        add_shortcode( $this->short_code_name, $this->do_frontend_shortcode() );
    }

    protected function do_frontend_shortcode() {
        echo \'Test! \'.$this->metabox_id;
    }
}
子类

//test-form.php
    class TestForm extends ShortcodeHelper {

        /**
         * TestForm constructor.
         */
        public function __construct() {
            parent::__construct(
                //post_name_id
                \'about_us\',
                //short_code_name
                \'cmb-about-form\'
            );
        }
    }

    new TestForm();

1 个回复
SO网友:Jędrzej Chałubek

如果目标是类方法,则需要传递一个数组,其中first argument is class instancesecond is method name as string.

你的add_shortcode 线条应如下所示:

add_shortcode($this->short_code_name, array($this, \'do_frontend_shortcode\'));