如何获得当前类的所有属性,而不是它的父类(s)在PHP



如何获得当前类的所有属性的数组,不包括继承的属性?

你只能通过反射到达它,这里有一个合适的例子:

<?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;

相关内容

  • 没有找到相关文章

最新更新