Hello PHPians 😀

While working on a project i’ve face a bug in php5.3. In PHP4

get_object_vars($obj);

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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s