显示对象的所有公共属性(名称和值)

This thread didn't helped me.

If I use

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

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

I get

attrib1_name : attrib2_name : attrib3_name

There are no values. Also a private attribute is shown, which I don't want.

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 a private attribute and all sub attributes. But this time I have the values. How can I constrain this to one level?

Isn't there a possibility to show all public attributes with their values of an object?

You are seeing non-public properties because get_class_vars works according to current scope. Since you are using $this your code is inside the class, so the non-public properties are accessible from the current scope. The same goes for get_object_vars which is probably a better choice here.

In any case, a good solution would be to move the code that retrieves the property values out of the class.

If you do not want to create a free function for that (why? seriously, reconsider!), you can use a trick that involves an anonymous function:

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

See it in 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);

You can do this easily with php Reflection api

I Fully recognize what you are trying to achieve so why not have something external like this to help out... (pasted 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 "

";
print_r($ball1->allPropsToArray());

echo "

";

?>

This way I can both access all properties of the object or for something such as a database access layer or similarly for a function that send "safe" data to a view or another un-privileged model I can send just the public properties, but have the behaviour defined within the object.

Sure this leads to coupling with a utility class, but to be fair not all couplings are bad, some are nesecarry to achieve an end goal, dont get bogged down by these things