问题
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:
Base class:
class ABC {
function __construct() {
...
}
}
Extending class:
class DEF extends ABC {
function __construct() {
...
}
}
While the base class is always loaded, the other classes are loaded depending of the situation.
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?
回答1:
You can use an autoloader at the top of your file :
function __autoload($className) {
require_once $className . '.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();
}
}
回答2:
If you put all your classes in the same folder, and name them [class].php, you can put the following at the top of your script and they will all load magically
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
If they go into different folders, just implement your own scheme
Reference: http://php.net/manual/en/language.oop5.autoload.php
来源:https://stackoverflow.com/questions/17658721/proper-way-to-load-a-base-class-extended-class-in-php