admin管理员组

文章数量:1434909

I'm grabbing products from wc_get_products() and looping through them to display information in a foreach. Are there any benefits (performance or otherwise) to using $product->get_name() over $product->name or vice versa?

It appears you can pass a context variable into most of these get methods, so that seems like one benefit, but are there more?

I'm grabbing products from wc_get_products() and looping through them to display information in a foreach. Are there any benefits (performance or otherwise) to using $product->get_name() over $product->name or vice versa?

It appears you can pass a context variable into most of these get methods, so that seems like one benefit, but are there more?

Share Improve this question asked Apr 4, 2019 at 0:41 macondo_buendiamacondo_buendia 1051 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You should always use methods over accessing properties directly, when they're available.

Methods are the 'API' for the object, and by using them you don't need to worry about the internal structure of the object's data, and it theoretically allows the object to be designed so that its internal structure can change without affecting code that consumes it. In a lot of code the properties are actually made impossible to access without a method. For backwards compatibility WooCommerce hasn't done this, and likely won't change the data structure for the same reason reason, but its best practice and you should get in the habit of using the methods.

In WooCommerce specifically, it also ensures that the value is passed through the woocommerce_product_get_name filter, which means that the value will properly reflect any modifications made by other plugins the user might be running. For example, the user might be running a plugin that uses the woocommerce_product_get_price filter to convert the price to an appropriate value for another currency. If your code uses $product->price instead of $product->get_price() then you'll be using the incorrect value in that context.

本文标签: woocommerce offtopicBenefits over using object method over property from product