动态子类生成 - PHP
我有一个抽象的“对象”类,它提供基本的 CRUD 功能以及验证等。通常,我会使用 __autoload($name) 魔术函数来加载一个存在于其自己文件中的类,该类的名称与我的类相同希望懒加载。代码看起来像这样,正如你可以想象的那样,它变得相当重复。
final class bicycle extends object {
public function __construct($id=null) {
parent::__construct($id, __CLASS__);
}
public function __toString() {
return($this->name);
}
}
我的问题是我是否可以以某种方式动态生成这些类,这样我就不必一遍又一遍地创建相同的功能 - 从而减少开销和设计时间。 PHP5 是否支持此功能,或者我只是高估了 OO PHP 的功能?
谢谢!
I have an abstract "object" class that provides basic CRUD functionality along with validation, etc. Typically I would use the __autoload($name) magic function to load a class that would exist in its own file, named the same as the class I wish to lazy load. The code would look something like this, which as you can imagine becomes quite repetitive.
final class bicycle extends object {
public function __construct($id=null) {
parent::__construct($id, __CLASS__);
}
public function __toString() {
return($this->name);
}
}
My question is whether or not I can somehow dynamically generate these classes on the fly so I don't have to create the same functionality over and over - thus reducing overhead and design time. Does PHP5 even support this or am I simply overestimating the power of OO PHP?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与其复制粘贴此内容,为什么不将 __construct 和 __toString 方法的代码放在
object
类的定义中?像这样的事情应该做:
并且,调用它:
你会得到:
这意味着类
bicycle
的实例,名称为property
的值正确。无需复制粘贴任何代码——除了
bicycle
类本身的定义。作为旁注,如果您确实想动态生成一个类,您可能可以使用如下内容:
您只需动态构造
$code
变量即可。但是我强烈建议不要这样做:
new bike
”感觉是错误的!eval
肯定会对性能产生一些影响,声明一个新类并不是那么痛苦,而且我肯定更喜欢复制粘贴修改几行而不是使用这样的东西。
Instead of copy-pasting this, why don't you just put the code of the
__construct
and__toString
methods in the definition of yourobject
class ?Something like this should do :
And, calling it :
You get :
Which means an instance of class
bicycle
, with the nameproperty
at the right value.No need to copy-paste any code -- except for the definition of the
bicycle
class itself.As a sidenote, if you really want to generate a class dynamically, you can probably use something like this :
You just have to construct the
$code
variable dynamically.But I would strongly advise against this :
new bicycle
" without having declared the class feels wrong !eval
Declaring a new class is not such a pain, and I would definitly prefer copy-pasting-modifying a few line than use anything like this.
嗯,对于 __toString,你只需将它放在父类中即可。示例如下:
我不太确定您想要通过重写构造函数来传递 CLASS 来实现什么目的。
Well, for __toString, you just put it in the parent class. Example follows:
I'm not exactly sure what you're trying to accomplish with overriding the constructor to pass in CLASS.
PHP5 中不存在此功能。它可能在 PHP6 中可用,但由于还没有适用于 ubuntu 的软件包,我不会继续。
This functionality does not exist in PHP5. It may be available in PHP6, but since there is no package for ubuntu yet I will not proceed.