Php object-oriented full strategy (17th) automatic class loading. Automatic loading many developers create a PHP source file for each class definition when writing object-oriented applications. A big headache is that you have to automatically load classes in each script (each class has one
Many developers create a PHP source file for each class definition when writing object-oriented applications. A large
The headache is that you have to write a long list of contained files at the beginning of each script (each class is a file.
In a software development system, it is impossible to write all classes in a PHP file.
When you need to call the class declared in another file, you need to introduce this file through include. But sometimes,
Among the numerous file projects, it is a headache to include all the files of the required classes one by one.
Can we import the PHP file where this class is located when we use any classes? This is where we are.
The automatically loaded class to be discussed.
In PHP5, you can define a _ autoload () function, which is automatically called when trying to use a class that has not been defined.
By calling this function, the script engine has the last chance to load the required class before a PHP error fails,
_ A parameter received by the autoload () function is the class name of the class you want to load. Therefore, when you create a project
Class file names must follow certain rules. it is best to center the names of classes, or you can add a uniform prefix or suffix
File name, such as xxx_classname.php, classname_xxx.php, and classname. php.
In this example, we try to load the MyClass1 and MyClass2 classes in the MyClass1.php and MyClass2.php files respectively.
Code snippet
The code is as follows:
Function _ autoload ($ classname ){
Require_once $ classname. '. php ';
}
// The MyClass1 class does not automatically call the _ autoload () function. the input parameter "MyClass1"
$ Obj = new MyClass1 ();
// The MyClass2 class does not automatically call the _ autoload () function. the input parameter "MyClass2"
$ Obj2 = new MyClass2 ();
?>
When many developers write object-oriented applications, they create a PHP source file for each class definition. A big headache is that it has to be in every script (each class has...