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 badges1 Answer
Reset to default 1You 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
版权声明:本文标题:woocommerce offtopic - Benefits over using object method over property from $product? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745630730a2667258.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论