Solving PHP5.3 properties access using get_object_vars() method

Hello PHPians 😀

While working on a project i’ve face a bug in php5.3. In PHP4 [code]get_object_vars($obj);[/code] was returning only public proprties of the object while in php5.3 it’s also returning private properties.
For example if you try to run this code

<?php
    class user{
        public $username="alaa";
        private $password="1234";
         
        function get_user()
        {
            var_dump(get_object_vars($this));
        }
    }
     
    $user_data = new user();
    $user_data->get_user();
?>

output will be:

array
  'username' => string 'alaa' (length=4)
  'password' => string '1234' (length=4)  

Actually it’s not the end of the story. There’s a class that will got this bug solved. This magical class is called ‘ReflectionObject’ class.

you can use this handy function which takes an object as a parameter and returns and object contains only the public properties.

/**
 * return the public properties only, solving php5.3 bug issue
 */
function my_get_object_vars($obj) {
    $ref = new ReflectionObject($obj);
    $pros = $ref -> getProperties(ReflectionProperty::IS_PUBLIC);
    $result = array();
    foreach ($pros as $pro) {
        false && $pro = new ReflectionProperty();
        $result[$pro -> getName()] = $pro -> getValue($obj);
    }
 
    return $result;
}

now you can modify your class to test the function to be as follows

<?php
    class user{
        public $username="alaa";
        private $password="1234";
         
        function get_user()
        {
            var_dump(my_get_object_vars($this));
        }
    }
    /**
     * return the public properties only, solving php5.3 bug issue
     */
    function my_get_object_vars($obj) {
        $ref = new ReflectionObject($obj);
        $pros = $ref -> getProperties(ReflectionProperty::IS_PUBLIC);
        $result = array();
        foreach ($pros as $pro) {
            false && $pro = new ReflectionProperty();
            $result[$pro -> getName()] = $pro -> getValue($obj);
        }
 
        return $result;
    }
 
     
    $user_data = new user();
    $user_data->get_user();
?>

and auto-magically this will solve your bug 🙂
and here’s the output

array
  'username' => string 'alaa' (length=4)

Hope you enjoyed, thanks 🙂