English 中文(简体)
php动态类继承
原标题:php dynamic class inheritance

我知道我可以在运行时通过执行

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

我可以用这种方式

echo $obj->foo; //bar

如果要使$obj从现有类继承,该怎么办?

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{}

我想我可能会使用动态对象来避免这些无聊的东西。

问题回答

您可以始终执行eval(类User extends Model{}),但这不是一个好主意。实际上,你应该只在一个文件中创建类,然后操作码缓存就会正常工作,它可以被版本跟踪,等等。

tl;博士:定义模型类,这是正确的做法™.

如果真的没有其他方法,可以用我的Dynherit类创建一个“动态”继承。它创建了您想要的继承,但继承来自文件,并且只使用尚未加载的类。

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

GitHub链接:https://github.com/Komrod/Dynherit

严格地说,对于你的问题,我认为唯一可能的方法是使用Runkit,它允许您动态地重新声明类。不确定该解决方案的可移植性。

你可以使用原型设计模式来克隆一个对象,然后你可以在克隆的对象中添加你需要的一切





相关问题
Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

C++ Class Inheritance problem

Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class. class Instruction{ protected: string name; int value; public: Instruction(string ...

Overloading a method in a subclass in C++

Suppose I have some code like this: class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

Extending Flex FileReference class to contain another property

I want to extend the FileReference class of Flex to contain a custom property. I want to do this because AS3 doesn t let me pass arguments to functions through event listeners, which makes me feel sad,...

Interface Inheritance in C++

I have the following class structure: class InterfaceA { virtual void methodA =0; } class ClassA : public InterfaceA { void methodA(); } class InterfaceB : public InterfaceA { virtual ...

热门标签