如何通过自动加载在父类中伪装子类(php)
我有一个基类,它被大约十个子类继承。这些子类中的大多数都有非常相似的行为,但我只想为其中三个定义专门的方法。
是否可以通过每次实例化子类的对象时自动加载父类来伪装这些类的存在?这样我就不必用相同的代码定义多个类了?
例如
class ParentClass {
public function __construct() {
switch(get_class($this)) {
case "ChildClass1" : do_stuff() break;
case "ChildClass2" : do_other_stuff() break;
default: break;
}
}
}
$c1 = new ChildClass1();
$c2 = new ChildClass2();
......只有一个文件 ParentClass.php
(没有单独的文件 ChildClass1.php
或 ChildClass2.php
)。
I have a base class that is inherited by about ten subclasses. Most of these subclasses have very similar behavior, but I want to define specialized methods only for three of them.
Is it possible to masquerade the existence of these classes, by autoloading the parent class every time an object of the child class is instantiated? This way I would not have to define multiple classes with the same code?
E.g.
class ParentClass {
public function __construct() {
switch(get_class($this)) {
case "ChildClass1" : do_stuff() break;
case "ChildClass2" : do_other_stuff() break;
default: break;
}
}
}
$c1 = new ChildClass1();
$c2 = new ChildClass2();
...and have only one file ParentClass.php
(no separate files ChildClass1.php
or ChildClass2.php
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你为什么不这样做呢?
Why don't you just do this?
您必须将逻辑添加到
__autoload()
函数或spl_autoload_register()
中,它通过字符串比较来决定要加载哪个文件/如果可能是一个文件你父母的孩子。You'd have to add the logic to the
__autoload()
function, or anspl_autoload_register()
, which by string comparison decides what file to load / if it possibly is one of the children of your parent.在我看来,维持每个文件一个类的约定是有益的。它使自动加载器保持简单,促进各个类的重用,最重要的是,使源代码更易于导航和推理。如果您有许多具有共同父级的类,请考虑将它们移动到单独的子目录并将该目录添加到自动加载器。
对于 PHP 以外具有更好导入语义的语言来说,情况不一定如此。
In my opinion it's beneficial to maintain the convention of one class per file. It keeps the autoloader straightforward, facilitates reuse of individual classes and, most importantly, makes the source code easier to navigate and reason about. If you have many classes with common parent, consider moving them to a separate subdirectory and add this directory to autoloader.
This is not necessarily true for languages other than PHP that have better import semantics.