php dynamic class inheritance

前提是你 提交于 2019-12-24 11:19:05

问题


I know I can generate a class at runtime by executing

$obj = (object)array('foo' => 'bar');+

this way I can use

echo $obj->foo; //bar

What if want to make $obj inherits from an existing class?

What I wanna achive: I'm forking paris project on github (https://github.com/balanza/paris). It's an active record class. I wonder I need to declare a class for every object, even if it's empty:

class User extends Model{}

I guess I might use dynamic object to avoid this boring stuff.


回答1:


You could always do eval('class User extends Model{}') but is not a good idea. Really, you should just create the class in a file, then opcode caching will work properly, it can be version tracked, etc etc.

tl;dr: Define the model class, it is the Right Thing To Do™.




回答2:


If there is really no other way for you to do it, you can create a "dynamic" inheritance with my Dynherit class. It creates the inheritance you want but from files and only with classes you didnt already loaded.

Download v0.62 : http://optimisationphp.komrod.com/source/sha/test/dynamic_inheritance_01/dynherit_v0.62.zip

GitHub link : https://github.com/Komrod/Dynherit




回答3:


Strictly to your question, the only way I can see it possible is by using Runkit, which let's you re-declare classes on the fly. Not sure how portable that solution is.



来源:https://stackoverflow.com/questions/4924616/php-dynamic-class-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!