php反射获取属性而不获取基类的属性 [英] php reflection get properties without getting properties of base class

查看:47
本文介绍了php反射获取属性而不获取基类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在使用一个设置类,它扩展了一个类似于全局设置"的基本设置类.有几个服务,每个服务都有自己的设置类,它扩展了抽象的基本设置类.抽象基本设置类对应于服务之间共享的设置.所以首先我会用下面的例子来说明,然后我会定义问题:

So I am working with a settings class that extends a base settings class that would be similar to a "global settings". There are several services and each service has its own settings class that extends the abstract base settings class. The abstract base settings class corresponds to settings that are shared between services. So first I will illustrate with an example below and then I will define the problem:

示例:

abstract class BaseSettings {
    protected $settingA;
    protected $settingB;
}

class MyServiceSettings extends BaseSettings {
    private $settingC;
    public $settingD;
}

问题:

如果我像这样创建一个 ReflectionClass 实例..

If I create a ReflectionClass instance like so..

$reflect = new ReflectionClass($this);

..从 MyServiceSettings 类或 BaseSettings 类(因为显然您不能拥有抽象类的实例),$reflect->getProperties() 将始终返回属性MyServiceSettings 和 BaseSettings(我想这是合适的,因为我们真的在使用一个具体的类)

..from either the MyServiceSettings class or the BaseSettings class (because obviously you can't have an instance of an abstract class), $reflect->getProperties() will always return the properties of both MyServiceSettings and the BaseSettings (and I guess that's appropriate because we're really working with a single concrete class)

现在我确定我可以创建一个空类来扩展抽象 BaseClass 以找出哪些属性去哪里(或者只是摆脱抽象并创建 BaseClass 的实例),但这看起来相当混乱,所以我我想知道是否有更优雅的方法来确定哪些属性属于父类,哪些属于子类?

Now I am sure I could create an empty class that extends the abstract BaseClass to figure out which properties go where (or just get rid of the abstract and create an instance of the BaseClass), but that seems rather messy, so I am wondering if there is, perhaps, a more elegant way to determine which properties belong to the parent class and which belong to the child class?

如果您好奇我为什么要这样做 - 我正在将设置序列化为 .json 文件,以实现我添加的恢复功能,以便可以从上次成功完成的最后一个原子操作继续.为什么我必须这样做 - 环境的限制.

If you are curious why I am even doing this - I am serializing the settings to a .json file for the purposes of a recovery feature I added so that one can continue from the last atomic operation that last successfully completed. Why I have to do it this way - limitation of the environment.

推荐答案

我会这样理解:

$class = new ReflectionClass('Some_class_name');
$properties = array_filter($class->getProperties(), function($prop) use($class){ 
    return $prop->getDeclaringClass()->getName() == $class->getName();
});

所以基本上获取所有属性并遍历它们,检查它们是否在我们反射的类中声明.

So basically get all properties and iterate through them checking if they were declared in class we reflected.

这篇关于php反射获取属性而不获取基类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆