This is also one of the basic ideas of OO design. Before PHP5, if you need to use a class, just use Include/require to include it directly. The following is a practical example:
Copy the Code code as follows:
Class classa{
Public Function __construct () {
echo "ClassA load success!";
}
}
Defines a class ClassA, with a file name of classa.php
Class classa{
Public Function __construct () {
echo "ClassA load success!";
}
}
Class ClassB extends ClassA {
Public Function __construct () {
Parent::__construct ();
echo "ClassB load success!";
}
}
Define a class ClassB with file name CLASSB.PHP,CLASSB inheritance ClassA
Class ClassB extends ClassA {
Public Function __construct () {
Parent::__construct ();
echo "ClassB load success!";
}
}
After defining the two test classes, let's write a PHP run program file containing the __autoload () method as follows:
function __autoload ($classname) {
$classpath = "./". $classname. PHP ';
if (file_exists ($classpath)) {
Require_once ($classpath);
}
else{
echo ' class file '. $classpath. ' Not found! ';
}
}
$newobj = new ClassA ();
$newobj = new ClassB ();
The operation of this file is a bit of a problem, it can be seen how good autoload ah, hehe ...
But I have to remind you that there are several aspects that must be noted.
1. If the class has an inheritance relationship (for example: ClassB extends ClassA), and ClassA is not in the directory where ClassB is located
Using the __autoload magic function to instantiate a CLASSB can be a fatal error:
Fatal error:class ' CLASSD ' not found in ... Classb.php on line 2,
Workaround: Place all classes that have extends relationships in the same file directory, or manually include the inherited classes in the file when instantiating an inheriting class;
2, another need to note is that the class name and the name of the class must be consistent, in order to more convenient use of magic function __autoload;
Other things to keep in mind:
3. This method is invalid when running PHP script in CLI mode;
4. If your class name is related to the user's input-or depends on the user's input, be sure to check the input file name, for example: /./such a file name is very dangerous.
The above describes the use of the plant vs. zombie modifier using the PHP __autoload function (auto-load class file), including the use of the plant vs. zombie modifier, and hopefully a friend who is interested in PHP tutorials will be helpful.