如何获得当前类的所有属性的数组,不包括继承的属性?
你只能通过反射到达它,这里有一个合适的例子:
<?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',
)
In PHP>= 5.3
$ref = new ReflectionClass('DerivedClass');
$ownProps = array_filter($ref->getProperties(), function($property) {
return $property->class == 'DerivedClass';
});
print_r($ownProps);
可以:
$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;