【问题标题】:How to get all properties of the current class and NOT its parent(s) in PHP如何在 PHP 中获取当前类而不是其父类的所有属性
【发布时间】:2015-10-29 04:51:38
【问题描述】:

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

【问题讨论】:

  • 子类中不需要的属性,在父类中将它们设为私有。您能否详细说明您要对属性数组做什么?
  • 检查后期静态绑定是否有用。 php.net/manual/en/language.oop5.late-static-bindings.php
  • Laravel 作业类作为 DTO。但是,如果它们是可排队的,它们会从其父级使用的特征中继承两个额外的属性。如果有一个本机函数来消除父类属性以仅具有 DTO 的值以便于处理,那就太好了。我不能只按名称排除它们,因为它可能会随着未来的 laravel 更新而中断,其中可能会添加更多内容或它们的名称可能会更改。
  • 我同意@Jigar;如果您需要这样做,那么首先使用继承编写它是一个错误。通过使用装饰器模式或仅使用嵌套对象编写类,您可以获得与您正在寻找的结果相似的结果,而无需打破 OOP 的基本概念。

标签: php class oop object reflection


【解决方案1】:

在 PHP >= 5.3

$ref = new ReflectionClass('DerivedClass');  
$ownProps = array_filter($ref->getProperties(), function($property) {
    return $property->class == 'DerivedClass'; 
});  

print_r($ownProps);

【讨论】:

    【解决方案2】:

    你只能通过反射来达到它,这里是合适的例子:

    <?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',
    )
    

    【讨论】:

      【解决方案3】:

      这将起作用:

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

      【讨论】:

        猜你喜欢
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 2013-01-16
        相关资源
        最近更新 更多