我如何在woocommerce中使用wc()?

byr*_*gur 7 php oop wordpress woocommerce

我正在努力wc()在woocommerce中使用该功能.文档说明了这一点Returns the main instance of WC to prevent the need to use globals.

我找不到任何使用这个的例子,我想知道如何使用wc()来做一些基本的事情.据我所知,它返回了主要的woocommerce实例; 从中我可以提取出我需要的所有数据; 但我不知道正确使用的语法......可能是这样的吗?

$foo = WC();
$bar = $foo->cart;
echo $bar;
Run Code Online (Sandbox Code Playgroud)

有人可以纠正这个.

此外,我试图了解这样做的优点,而不是全局化变量.

Rei*_*gel 12

正如链接中的文档所说的那样.'防止需要使用全局变量'.一个例子就是这样......

代码使用全局.

global $woocommerce;
$customer_country = $woocommerce->customer->get_country();
Run Code Online (Sandbox Code Playgroud)

代码不使用全局

$customer_country = WC()->customer->get_country(); 
// some servers may not like like this... best is to use variables like $foo = WC(); then use $foo->customer->get_country()...
Run Code Online (Sandbox Code Playgroud)

如何使用WC()?从这里开始 ......

我为什么要避免全球化?

  • @Fahmi现在你让我做了一些研究!版本3.2.6有WC()但版本3.4.0有wc().文档使用wc,但是他们的URL有WC ......简而言之,似乎它们被用于可交换的事物中.它没关系,因为PHP不区分大小写.https://docs.woocommerce.com/wc-apidocs/function-WC.html (2认同)