php动态类继承
在运行时生成一个类,
$obj = (object)array('foo' => 'bar');+
我知道我可以通过执行这种方式
echo $obj->foo; //bar
如果想让 $obj 继承现有的类,我可以使用What if Want to make $obj 继承现有的类?
我想要实现的目标: 我正在 github 上分叉 paris 项目 (https://github.com/balanza/paris)。这是一个活跃的记录类。我想知道我需要为每个对象声明一个类,即使它是空的:
class User extends Model{}
我想我可能会使用动态对象来避免这种无聊的事情。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您始终可以执行
eval('class User extends Model{}')
但这不是一个好主意。实际上,您应该在文件中创建该类,然后操作码缓存将正常工作,它可以进行版本跟踪等。tl;dr:定义模型类,这是正确的事情™。
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™.
如果确实没有其他方法可以做到这一点,您可以使用我的 Dynherit 类创建“动态”继承。它创建您想要的继承,但来自文件并且仅使用您尚未加载的类。
下载 v0.62 : http://optimizationphp.komrod.com/ source/sha/test/dynamic_inheritance_01/dynherit_v0.62.zip
GitHub 链接:https://github.com /科姆罗德/Dynherit
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
严格来说,对于你的问题,我能看到它的唯一方法是使用 Runkit ,这让您可以动态重新声明类。不确定该解决方案的便携性如何。
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.
您可以使用原型设计模式来克隆一个对象,然后您可以在克隆的对象中添加您需要的所有内容
You can use a Prototype design pattern to clone an object, then you can add everything you need in cloned one