获取继承树中 PHP 对象的祖先
我有一个对象,想要列出所有父类,直到 stdClass 或其他类。
我已经在我的数据库表(比如类别)中添加了一个多态字段,并且想要自动化我的查找方法,以便也返回超类,这样我可以在我知道不一定是最终子类的点跳入继承树:
FoodCategory::find_by_id(10) === Category::find_by_id(10)
SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');
大致我猜:
function get_class_lineage($object){
$class = get_parent_class($object);
$lineage = array();
while($class != 'stdClass'){
$dummy_object = new $class();
$lineage[] = $class = get_parent_class($dummy_object);
}
return $lineage;
}
但这实例化了一个对象,有谁知道如何实现这一目标?
感谢您的任何意见,我觉得我在这里遗漏了一些明显的东西。
I have an object and want to list all parent classes up until stdClass or whatever.
I have added a polymorphic field to my database table (say categories) and want to automate my finder method so that super classes are also returned, this way i can jump into the inheritance tree at a point i know not necessarily the final subclass:
FoodCategory::find_by_id(10) === Category::find_by_id(10)
SELECT * FROM categories WHERE ..... AND type IN ('FoodCategory', 'Category');
Roughly i guess:
function get_class_lineage($object){
$class = get_parent_class($object);
$lineage = array();
while($class != 'stdClass'){
$dummy_object = new $class();
$lineage[] = $class = get_parent_class($dummy_object);
}
return $lineage;
}
But this instantiates an object, does anyone know how to achieve this without?
Thanks for any input, i feel like i'm missing something obvious here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用反射
ReflectionClass 接受以下名称类或对象。
Using Reflection
ReflectionClass accepts either the name of the class or an object.
在被指出重复的问题后,我去了:
标准库中的 class_parents 函数是我忽略的明显事情。
我认为反射对于这个简单的任务来说太过分了。
After being pointed to the duplicate question i have gone for:
The class_parents function from the standard library was the obvious thing i was overlooking.
I thought Reflection was overkill for this simple task.
正如您可以在手册中阅读的那样,您还可以将类名作为字符串提供给函数。
这里索引
0
是对象本身的类名:As you can read at manual you can also give a classname as a string to the function.
Here index
0
is the classname of the object itself: