mhopkins321
mhopkins321

Reputation: 3073

Accessing "protected" part of object

I have the variable $customerData that stores an object. When I execute print_r($customerData) I get something similar to the below.

Balanced\Customer Object(
    [_collection_uris:protected] => Array(
        [reversals] => Array(
            [class] => Balanced\Reversal
            [uri] => /v1/customers/1234123412341234/reversals
        )
    )
    [_member_uris:protected] => Array(
        [source] => Array(
                [class] => Balanced\Card
                [uri] => /v1/customers/1234123412341234/cards/987698769876
            )
    )
    [_type] => customer
    [twitter] => twitterHandle
    [phone] => 5551231234
)

I'm having issues accessing the uri inside _member_uris:protected.

print_r($customerData->_member_uris:protected); #Throws error "unexpected ':'"
print_r($customerData->_member_uris); #Throws error " Undefined property"
print_r($customerData['_member_uris']); #Throws error "Cannot use object of type array"

What is the process of accessing that part of the object?

Upvotes: 0

Views: 65

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Members declared protected can be accessed only within the class itself and by inherited and parent classes. You could add a method in your class to get it, using setAccessible(), like:

//function inside your class
public static function getProtectedProp($class, $propName) {
    $reflClass = new ReflectionClass($class);
    $property = $reflClass->getProperty($propertyName);
    $property->setAccessible(true);     
    return $property->getValue($class);
}

and you can do:

getProtectedProp($someClassObject, 'protectedPropertyName');

Source:: Reading Protected Property

Upvotes: 1

Barmar
Barmar

Reputation: 780724

You can't access protected or private properties from global code or regular functions. From the documentationof Visibility:

  • Class members declared public can be accessed everywhere.
  • Members declared protected can be accessed only within the class itself and by inherited and parent classes.
  • Members declared as private may only be accessed by the class that defines the member.

Upvotes: 1

Related Questions