How to get protected property of object in PHP

object, php, php-5.2, protected

Solution

That's what "protected" is meant for, as the Visibility chapter explains:

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

If you need to access the property from outside, pick one:

- Don't declare it as protected, make it public instead

- Write a couple of functions to get and set the value (getters and setters)

If you don't want to modify the original class (because it's a third-party library you don't want to mess) create a custom class that extends the original one:

class MyFields_Form_Element_Location extends Fields_Form_Element_Location{
}

... and add your getter/setter there.

Problem

I have a object having some protected property that I want to get and set. The object looks like ``` Fields_Form_Element_Location Object ( [helper] => formText [_allowEmpty:protected] => 1 [_autoInsertNotEmptyValidator:protected] => 1 [_belongsTo:protected] => [_description:protected] => [_disableLoadDefaultDecorators:protected] => [_errorMessages:protected] => Array ( ) [_errors:protected] => Array ( ) [_isErrorForced:protected] => [_label:protected] => Current City [_value:protected] => 93399 [class] => field_container field_19 option_1 parent_1 ) ``` I want to get `value` property of the object. When I try `$obj->_value` or `$obj->value` it generates error. I searched and found the solution to use `PHP Reflection Class`. It worked on my local but on server PHP version is `5.2.17` So I cannot use this function there. So any solution how to get such property?

Original source