Php Woocommerce Xero功能不起作用-“;错误:";使用$this…“;

Php Woocommerce Xero功能不起作用-“;错误:";使用$this…“;,php,wordpress,function,filter,woocommerce,Php,Wordpress,Function,Filter,Woocommerce,我在woocommerce xero插件中具有以下功能 /** * @return string */ public function get_name() { return apply_filters( 'woocommerce_xero_contact_name', $this->name, $this ); } 我需要换衣服 'woocommerce\u xero\u contact\u name',$this->name,

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

   /**
     * @return string
     */
    public function get_name() {
        return apply_filters( 'woocommerce_xero_contact_name', $this->name, $this );
    }
我需要换衣服

'woocommerce\u xero\u contact\u 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' );
知道我做错了什么吗


谢谢

请尝试以下内容并让我知道,因为这根本没有经过测试---


无法命名函数参数
$this

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

您连接到一个过滤器,该过滤器有两个参数,一个名称和一个类实例。您需要在筛选器中同时接受这两个选项,以便使用计费公司覆盖名称

// 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 );
在您的评论之后,我想补充一些关于
$xero
的内容

筛选器接受两个参数:联系人的当前名称和对对象的引用。然后,您的回调将返回一个字符串,在本例中,该字符串将是计费公司

// 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 );
使用伪变量
$this
将对象实例传递到回调中。但是,您不能在回调中命名参数
$this
。你需要给它起个名字


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

感谢您的评论,我理解您的意思,直到return$xero->billing_company;这是原始文件,如果它有助于识别对象?对象是它所在的类吗?@Jonnygogo我更新了我的答案,试图提供更多的清晰性。我不理解这部分($name,$this){第一个是传递给过滤器的名称,第二个是对象,正如nathan用$xero回答的一样,我只是不想更改您的变量名。