How to obtain the name of the protected properties of an object without the asterisks?

Asked

Viewed 24 times

0

It is possible to obtain only the name of the protected properties of an object without the asterisk symbol (*).

class Person {
    protected $name;
    protected $age;
}

$person = new Person();

print_r(array_keys((array) $person)); //Array ( [0] => *name [1] => *age )

The goal would be Array ( [0] => name [1] => age ).

Is there a PHP function for this?

1 answer

2


Since the idea is to inspect an object, do it correctly with the classes of Reflection:

$reflect = new ReflectionObject($person);
$protected = $reflect->getProperties(ReflectionProperty::IS_PROTECTED);

print_r($protected);

The method getProperties will return the properties of the object and, as defined the parameter ReflectionProperty::IS_PROTECTED, will return only those who are protected.

The way out:

Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

)

If you just want the list of property names:

array_column($protected, 'name')

What would return:

Array
(
    [0] => name
    [1] => age
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.