【问题标题】:Woocommerce Xero function not working - "Error: "Using $this..."Woocommerce Xero 功能不起作用 - “错误:“使用 $this ...”
【发布时间】:2017-05-19 21:44:49
【问题描述】:

我在 woocommerce xero 插件中有以下功能。

   /**
     * @return string
     */
    public function get_name() {
        return apply_filters( 'woocommerce_xero_contact_name', $this->name, $this );
    }

我需要改变

'woocommerce_xero_contact_name', $this->name, $this );

到这里

'woocommerce_xero_contact_name', $this->billing_company, $this );

当我尝试为我的functions.php 编写函数时,我不断收到错误消息:“不在对象上下文中使用$this”,我不明白。

我的函数现在是这样的;

public function xero_contact_name_1( $this ) {


    return $this->billing_company;
}
add_filter( 'woocommerce_xero_contact_name', 'xero_contact_name_1' );

任何想法我做错了什么?

谢谢

【问题讨论】:

    标签: php wordpress function filter woocommerce


    【解决方案1】:

    你不能命名函数参数$this

    当从对象上下文中调用方法时,伪变量 $this 可用。 $this 是对调用对象的引用(通常是方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。

    http://www.php.net/manual/en/language.oop5.basic.php

    您正在连接一个过滤器,该过滤器有两个参数,一个名称和一个类的实例。您需要在过滤器中同时接受这两个选项,才能使用帐单公司覆盖名称。

    // This is a function, not a method, so drop public.
    function xero_contact_name_1( $name, $xero ) {
    
        // I don't know what the object is so I'm referring to it as xero.
        return $xero->billing_company;
    }
    
    // 10 = default priority, 2 is the number of accepted args. Without that we won't get $xero.
    add_filter( 'woocommerce_xero_contact_name', 'xero_contact_name_1', 10, 2 );
    

    在您的 cmets 之后,我想补充一点关于 $xero 的信息。

    过滤器采用两个参数:联系人的当前名称和对对象的引用。然后,您的回调应返回一个字符串,在这种情况下将是计费公司。

    使用伪变量$this 将对象实例传递到您的回调中。但是,您不能在回调$this 中命名参数。你需要给它一个名字。

    我不熟悉这个对象实际上是什么,所以我只是将它称为$xero。然后,对象实例可作为$xero 而不是$this 用于您的回调函数。 return 语句返回对象的 billing_company 属性。

    【讨论】:

    • 感谢您的 cmets,直到 return $xero->billing_company; 我明白您的意思如果它有助于识别对象,这是原始文件吗? pastebin.com/QBfpSp5f
    • 对象会是它所在的类吗?
    • @Jonnygogo 我已经更新了我的答案以尝试提供更清晰的答案。
    【解决方案2】:

    尝试关注并告诉我,因为这根本没有经过测试 ---

    public function xero_contact_name_1($name, $this ) {
    
    
        return $this->billing_company;
    }
    add_filter( 'woocommerce_xero_contact_name', 'xero_contact_name_1', 10, 3);
    

    【讨论】:

    • 我不明白这部分($name, $this){
    • 第一个是传递给过滤器的名称,第二个是对象,正如 nathan 用 $xero 回答的那样,同样,我只是不想更改您的变量名称。
    猜你喜欢
    • 2013-11-02
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多