Show all public attributes (name and value) of an object

This thread didn't help me.

If i use

$class_vars = get_class_vars(get_class($this));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

      

I get

attrib1_name: attrib2_name: attrib3_name

No values. Also shown is a private attribute that I don't need.

If i use

echo "<pre>";
print_r(get_object_vars($this));
echo "</pre>";

      

I get

Array ([atrrib1_name] => attrib1_value [attrib2_name] => attrib2_value)

Here again I have the private attribute and all the auxiliary attributes. But this time I have values. How can I limit this to one level?

Isn't it possible to show all public attributes with their object values?

+3


source to share


4 answers


You see non-public properties because it get_class_vars

works according to the current scope . Since you are using $this

, your code is inside a class, so non-public properties are available from the current scope. The same goes for get_object_vars

, which is probably the best choice here.

Anyway, a good solution would be to move the code that fetches property values ​​from the class.

If you don't want to create a free function for this (why? Seriously, change your mind!), You can use a trick that involves an anonymous function:

$getter = function($obj) { return get_object_vars($obj); };
$class_vars = $getter($this);

      



Look at the action .

Update: . Since you are in PHP <5.3.0, you can use this equivalent code:

$getter = create_function('$obj', 'return get_object_vars($obj);');
$class_vars = $getter($this);

      

+5


source


You can do it easily with php Reflection api



+1


source


-1


source


I totally understand what you are trying to achieve, so why not have something external like this to help ... (inserted from PHPFiddle)

<?php

final class utils {
    public static function getProperties(& $what) {
        return get_object_vars($what);
    }
}
class ball {
    var $name;
    private $x, $y;

    function __construct($name,$x,$y) {

    }

    function publicPropsToArray() {
        return utils::getProperties($this);
    }
    function allPropsToArray() {
        return get_object_vars($this);
    }
}

$ball1 = new ball('henry',5,6);
//$ball2 = new ball('henry',3,4);

echo "<pre>";
print_r($ball1->publicPropsToArray());
echo "\r\n\r\n";
print_r($ball1->allPropsToArray());

echo "\r\n\r\n";

?>

      

This way I can both access all the properties of an object or anything like the database access layer or similar for a function that sends "safe" data to a view or some other unprivileged model, I can only send public properties, but have behavior defined within the object.

I'm sure this leads to a connection with a utility class, but to be honest, not all connections are bad, some of them are not needed to achieve the final goal, do not get bogged down in these things.

-1


source







All Articles