php可以在不先实例化类的情况下调用非静态方法吗?

Rom*_*man 1 php wordpress

我在我的 WordPress 插件中注册了操作的类方法。当我的方法被 Wordpress 调用时,如果我尝试使用 $this 变量,php 会抛出一个错误,指出在对象上下文之外调用 $this 变量是非法的。

怎么可能?我认为除非该方法是静态的,否则如果该类未实例化,您就不应该能够调用类方法!我的方法不是静态的!怎么了?

源代码


显然,初始化是从主插件文件中调用的:

add_action('init', array('AffiliateMarketting', 'initialize'), 1);
Run Code Online (Sandbox Code Playgroud)

我的班级是这样的:

class AffiliateMarketting 
{
    public function __construct()
    {
        // some initialization code
    }

    public function initialize()
    {
        add_action('woocommerce_before_single_product', array("AffiliateMarketting", "handleAffiliateReferral"));
    }

    public function handleAffiliateReferral($post)
    {
        $this->xxx();  // <---- offending function call
    }

    public function xxx()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

收到的错误信息实际上是Fatal error: Using $this when not in object context in <filename> on line <linenumber>

小智 5

您必须首先实例化该类。像这样的东西:

$affiliatemarketing = new AffiliateMarketing;
Run Code Online (Sandbox Code Playgroud)

然后执行以下操作:

add_action('init', array(&$affiliatemarketing, 'initialize'), 1);
Run Code Online (Sandbox Code Playgroud)

编辑:忘记添加,您的方法中的操作应该像这样添加:

add_action('woocommerce_before_single_product', array(&$this, "handleAffiliateReferral"));
Run Code Online (Sandbox Code Playgroud)