如果您使用的是 < PHP 5.3,并且需要获取私有属性和值,您可以使用此方法
这是您正在做的事情
<?php
$obj_with_privates = new MyObject();
$class = get_class($obj_with_privates);
$vars = get_object_vars($obj_with_privates);
print_r($vars);
$reflection = new ReflectionClass( $class );
$attributes = $reflection->getProperties();
print_r($attributes);
?>
这是您应该做的事情
<?php
$obj_with_privates = new MyObject();
$class = get_class( $obj_with_privates );
$reflection = new ReflectionClass( $class );
$abstract = $reflection->getMethods( ReflectionMethod::IS_ABSTRACT );
$priv_attr = $reflection->getProperties( ReflectionProperty::IS_PRIVATE );
$privates = array();
$parent = get_parent_class( $class );
$child = $class;
$constructor = $reflection->getConstructor();
$abstr_methods = "";
if(sizeof($abstr_methods))
{
foreach($abstract as $method)
{
$mname = $method->name;
$abstr_methods .= "public function $mname(){return false;}";
}
}
if(sizeof($priv_attr))
{
$parseable = unserialize(str_replace("\0$class\0", "\0*\0", serialize($obj)));
foreach($priv_attr as $attribute)
{
$aname = $attribute->name;
$privates[$aname] = $parseable->$aname;
}
}
$temp_child_class = "temp" . str_replace("_", "", "$class");
$class_def = "
class $temp_child_class extends $class{
$constructor
public function reflect_getmyvars(){
return get_object_vars(\$this);
}
$abstr_methods
}
";
eval($class_def);
$tcobj =@ new $temp_child_class;
$vars = $tcobj->reflect_getmyvars();
$attribs = array_merge($vars, $privates);
print_r($attribs);
?>