Home » Php » wordpress – Cannot access php stdClass property on std class object

wordpress – Cannot access php stdClass property on std class object

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m passing an ACF std class object of values to a function as a value and when trying to read it in the function, it shows up as an object but when I try to access a property Notice: Trying to get property “type” of non-object

function createACFProductLicenses($acfData, $propertyString){
    $newData = array();
    if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {

            print_r($value);
            // prints out
            // stdClass Object
            // (
            //   [type] => standard
            //   [item_id] => 727
            // )

            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}
// example of how I'm calling it:
// $product['acf'] is an stdClass of acf properties
createACFProductLicenses($product['acf'], 'product_licenses');
How to&Answers:

The “foreach” set the data structure to $key=>$value or [type] is a $key and “standard” is a $value so you can’t print $value->type because the object is actually ‘type’ => ‘standard’.
Also, know that the “foreach” will run your code for each item on the object like for ana array, so you can’t just print a specific value when you have different $key.

If you want to display all the items use this:

print_r($key.':'.$value) // this will print:  type : standard

Or if you want to only print the [Type] item Try this out:
insted of this

 if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {
            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}

Try this

if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        print_r($data['type']);
    }
}

I hope this will help, let me know if it didn’t work.