我正在尝试获取由类定义的属性列表(类变量)。这可以使用get_class_vars()
完成。不幸的是,我也需要了解这些变量的范围(公共/私人/受保护)。
<?php
class test {
public $publicProperty = 1;
protected $protectedProperty = 2;
private $privateProperty = 3;
public function getClassVars() {
return get_class_vars(__CLASS__);
}
}
$test = new test();
var_dump($test->getClassVars());
输出:
array(3) {
["publicProperty"]=> int(1)
["protectedProperty"]=> int(2)
["privateProperty"]=> int(3)
}
有没有办法获得范围,以便我可以获得例如property $protectedProperty
是受保护的var?
背景:仍然试图找到一个解决我已经在我的问题Changed behavior of (un)serialize()?中描述的令人讨厌的php bug的工作
答案 0 :(得分:2)
您应该使用ReflectionClass
<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}
$foo = new Foo();
$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
foreach ($props as $prop) {
print $prop->getName() . "\n";
}
var_dump($props);
?>
答案 1 :(得分:0)
以防某人需要解决上述问题。
根据@Kelvin的回答,我想出了以下实现。
<?php
class TestClass {
public $publicProperty = 1;
protected $protectedProperty = 2;
private $privateProperty = 3;
/**
* Returns an associative array of structure scope => property names
* @return array
**/
public function getPropertiesByScope() {
$properties = [];
$scopes = [
ReflectionProperty::IS_PUBLIC => 'public',
ReflectionProperty::IS_PROTECTED => 'protected',
ReflectionProperty::IS_PRIVATE => 'private'
];
foreach($scopes as $scope => $name) {
$properties[$name] = [];
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties($scope);
foreach($props as $p) {
$properties[$name][] = $p->name;
}
}
return $properties;
}
}
$test = new TestClass();
var_dump($test->getPropertiesByScope());
?>
输出:
array(3) {
["public"]=>
array(1) {
[0]=>
string(14) "publicProperty"
}
["protected"]=>
array(1) {
[0]=>
string(17) "protectedProperty"
}
["private"]=>
array(1) {
[0]=>
string(15) "privateProperty"
}
}