编辑:
看来你使用的是自己的PHP对象的属性是什么定义,所以让我给你我的。
PHP文档对于主题有些模糊,有些功能如get_object_vars
有点误导,因为它们将获取对象属性而不是变量。
据我的理解,是什么它归结为是:PHP使得类性能之间的区别(在编译时已知),并动态特性(即设置没有那些已被宣布)。
它与设置属性有关(因为它会创建一个动态的属性),但重点是要知道属性是否在类定义内部声明。
如果实际上你感兴趣的类和对象属性之间的这种差异,你可能会发现API的快乐,尽管如果你问我,我发现它使用起来极其尴尬。
此API的主要优点是,您可以列出将从当前范围(通常为受保护或私有成员)无法访问的属性。
如果您只是使用get_object_vars
或get_class_vars
函数,则会忽略所有私有/受保护属性,除非您在对象本身内定义一个方法(继承调用get_class_vars
的类将允许您获取受保护的属性,但不能访问私有那些)。
function list_properties($obj, $filter = null)
{
if ($filter === null) $filter = ReflectionProperty::IS_STATIC
| ReflectionProperty::IS_PUBLIC
| ReflectionProperty::IS_PROTECTED
| ReflectionProperty::IS_PRIVATE;
$spy = new ReflectionClass ($obj);
$class_properties = $spy->getProperties($filter);
echo "class:<br />";
foreach ($class_properties as $prop)
{
$name = $prop->getName();
$p = $spy->getProperty ($name);
$p->setAccessible(true);
$value = $p->getValue($obj);
echo "$name ("; var_dump($value); echo ")<br />";
}
echo "<br />object:<br />";
foreach ($obj as $property => $value)
{ echo "$property ("; var_dump($value); echo ")<br />"; }
}
class foo {
protected $class_protected;
private $class_private;
public $class_public;
private static $static_protected = "azerty";
private static $static_private = "qsdfgh";
public static $static_public = "wxcvbn";
}
$v = new foo();
$v->dynamic = "xxx";
list_properties($v);
// the ReflectionClass filter flags semantic is broken,
// so filtering becomes soon a cruel pain in the *ss
/*
* I leave it to the reader as an execrise to coax the bloody thing
* into giving you only the static public class properties, for instance.
*/
list_properties($v, ReflectionProperty::IS_STATIC|ReflectionProperty::IS_PUBLIC);
一种方法是将您的属性转换为该类内的本地数组。好处是可以使用array_filter(),它将返回一个数组减去原始数组中的空键。 http://us2.php.net/manual/en/function.array-filter.php – Rottingham
@kuroineko http:// stackoverflow。com/questions/21050862 /高效的方法来检查堆栈的非空属性#comment31651251_21050976 – user2679413