user197192
user197192

Reputation: 25

PHP - Trying to access a value in an object

It's a woocommerce object called $_product

When I var_dump it I get:

object(WC_Product_Variation)#4358 (13) {
  ["post_type":protected]=>
  string(17) "product_variation"
  ["parent_data":protected]=>
  array(16) {
    ["title"]=>
    string(7) "Antares"
    ["status"]=>
    string(7) "publish"
    ["sku"]=>
    string(0) ""

When I echo $_product->post_type; I get product_variation as expected, but I can't access the status value!

var_dump($_product->parent_data); gives me nothing (empty)

Why?

Upvotes: 0

Views: 74

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43581

You can't access protected properties outside of the object instance or its parent instances. See Property Visibility on php.net for more info.

So why is it possible to access the $post_type even though it's protected? Well, someone was "smart" enough to define an exception from the rule in this magic getter method - https://woocommerce.github.io/code-reference/files/woocommerce-includes-legacy-abstract-wc-legacy-product.html#source-view.68

This is a bad practice and should not be used.

Instead, you can create your own class that extends the WC_Product_Variation and defines its own public getters getPostType() and getParentData(). Just don't forget to instantiate the MyWC_Product_Variation instead of WC_Product_Variation when you want to use the getters.

class MyWC_Product_Variation extends WC_Product_Variation
{
    public function getPostType(): string
    {
        return $this->post_type;
    }

    public function getParentData(): array
    {
        return $this->parent_data;
    }
}

Upvotes: 1

Related Questions