PHP: How to get public properties of object

Sometimes you need all public properties of an object. I've also met this problem. I tried to find some usable native function on php.net, but the only native solution is the ReflectionProperty class. I think It claims too much resource. I've written an own function that has solved this issue.

Let's see the function

* It gets all public properties of given $object.
* @param object $object It must be object.
* @return array that contains all public property name as key and their values. example:
* array('property1' => array('foo'), 'property2' => false);
function getPublicProperties($object) {
    $result = get_object_vars($object);
    if ($result === NULL or $result === FALSE) {
        throw new ValueException('Given $object parameter is not an object.');
    return $result;

Why does this function work so good?

This function works well when you call inside actual object either you call outside the object, because in both situation the function can see only public properties. The result is a hash. You can search faster on hash than in number indexed array: isset($hash['property']) or array_key_exists('property', $hash) is faster than in_array('property', $array) would be. So we are lucky because get_object_vars($object); returns with hash. The keys of this hash are the name of property.

Blog categories:  Web development

Add new comment