如何获取当前类的所有属性的数组,不包括继承的属性?
答案 0 :(得分:4)
在PHP中> = 5.3
$ref = new ReflectionClass('DerivedClass');
$ownProps = array_filter($ref->getProperties(), function($property) {
return $property->class == 'DerivedClass';
});
print_r($ownProps);
答案 1 :(得分:3)
你只能用反射来达到它,这里有一个合适的例子:
<?php
class foo
{
protected $propery1;
}
class boo extends foo
{
private $propery2;
protected $propery3;
public $propery4;
}
$reflect = new ReflectionClass('boo');
$props = $reflect->getProperties();
$ownProps = [];
foreach ($props as $prop) {
if ($prop->class === 'boo') {
$ownProps[] = $prop->getName();
}
}
var_export($ownProps);
结果:
array (
0 => 'propery2',
1 => 'propery3',
2 => 'propery4',
)
答案 2 :(得分:2)
这将有效:
$class = new ReflectionClass($className); // get class object
$properties = $class->getProperties(); // get class properties
$ownProperties = array();
foreach ($properties as $property) {
// skip inherited properties
if ($property->getDeclaringClass()->getName() !== $class->getName()) {
continue;
}
$ownProperties[] = $property->getName();
}
print_r($ownProperties;