Before understanding this function, let’s look at another function: __autoload.
1. __autoload
This is an automatic loading function. In PHP5, when we instantiate an undefined class, this function will be triggered. Look at the following example:
🎜🎜🎜🎜🎜🎜🎜🎜🎜?> 🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜index.php 🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜<?🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜function🎜 🎜__autoload(🎜🎜$class🎜🎜)
{🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$file🎜🎜=🎜🎜$class🎜🎜. 🎜🎜'.class.php'🎜🎜; 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜)
) { 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜🎜🎜🎜🎜 🎜🎜}🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜= 🎜🎜new🎜 🎜PRINTIT();🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜$obj🎜🎜->doPrint();🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜?>🎜🎜🎜🎜🎜🎜🎜 🎜🎜After running index.php, hello world will be output normally. In index.php, since printit.class.php is not included, when instantiating printit, the __autoload function is automatically called. The value of the parameter $class is the class name printit. At this time, printit.class.php is introduced. . 🎜🎜This method is often used in object-oriented, which can avoid writing too many reference files and also make the entire system more flexible. 🎜🎜2. spl_autoload_register() 🎜🎜Look at spl_autoload_register() again. This function has the same effect as __autoload. Let’s look at a simple example: 🎜🎜🎜 🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜<?🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜function🎜 🎜loadprint( 🎜🎜$class🎜🎜)
{🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$file🎜🎜=🎜🎜$class🎜🎜. 🎜🎜'.class.php'🎜🎜; 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜))
{ 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜spl_autoload_register(🎜 🎜'loadprint'🎜🎜); 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$obj🎜 🎜= 🎜🎜new🎜 🎜PRINTIT();🎜🎜🎜🎜🎜
Replace __autoload with the loadprint function. But loadprint will not be triggered automatically like __autoload. At this time, spl_autoload_register() will work. It tells PHP to execute loadprint() when it encounters an undefined class.
)
{
🎜🎜🎜🎜🎜🎜 🎜🎜$file🎜🎜= 🎜🎜$class🎜🎜. 🎜🎜'.class.php'🎜🎜; 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜))
{ 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜 🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜 🎜🎜}🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜spl_autoload_register(
🎜🎜array🎜🎜(🎜🎜'test'🎜🎜,🎜🎜'loadprint'🎜🎜)
);🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜//Another way of writing: spl_autoload_register( "test::loadprint"
); 🎜PRINTIT();🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 $obj🎜🎜->doPrint();🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜?>🎜🎜🎜🎜🎜🎜🎜🎜
🎜
The above has introduced the detailed explanation of the spl_autoload_register function, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials. 🎜
🎜
🎜
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn