在PHP中加载基类+扩展类的正确方法 [英] Proper way to load a base class + extended class in PHP
问题描述
我正在做一个个人项目,这是我第一次使用 OOP.我的项目有一个基类,由其他人扩展(基本设置).澄清一下,这就是我正在做的:
I am working on a personal project and it is the first time for me using OOP. My project has a base class, which is extended by others (basic setup). To clarify, this is what I am doing:
基类:
class ABC {
function __construct() {
...
}
}
扩展课程:
class DEF extends ABC {
function __construct() {
...
}
}
虽然总是加载基类,但会根据情况加载其他类.
While the base class is always loaded, the other classes are loaded depending of the situation.
我的问题是,动态加载正确的扩展类的正确方法是什么?我应该导入"两个 php 吗?我应该转换基类 ($x = new ABC()),然后从基类加载另一个类吗?
My question is, what is the proper way to dynamically load the right extended class? Should I 'import' both php? Should I cast the base class ($x = new ABC()), and then load the other class from the base class?
推荐答案
您可以使用 autoloader 在您的文件顶部:
You can use an autoloader at the top of your file :
function __autoload($className) {
require_once $className . '.php';
}
或者您可以在子类的构造函数中使用父类的构造函数并手动导入php文件:
Or you can use the parent class' constuctor in the child class' constuctor and import manually the php file :
require_once(your_file.php);
class DEF extends ABC {
function __construct() {
parent::__construct();
}
}
这篇关于在PHP中加载基类+扩展类的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!