PHP spl_autoload_register for automatic loading

Source: Internet
Author: User

Here we will talk about some features of this function through an experiment.

Function prototype
Bool spl_autoload_register ([callback $ autoload_function [, bool $ throw = true [, bool $ prepend = false])

Version compatibility
PHP 5> = 5.1.2

Experiment Process
Step 1: Use the spl_autoload_register () function to register the load () method.
Copy codeThe Code is as follows:
<? Php
Function load (){
Require_once 'lib. php ';
}
Spl_autoload_register ('load ');
?>


The lib. php file code is as follows:
Copy codeThe Code is as follows:
<? Php
Class className {
Function method (){
Echo 'a method in class ';
}
}

Function onlyMethod (){
Echo 'method only ';
}
?>

Note: The lib. php file is a className class and an onlyMethod function.

Step 2: Call the automatic loading class
Copy codeThe Code is as follows:
$ Class = new className ();
$ Class-> method ();
OnlyMethod ();

Output:
A method in class
Method only

(Instantiate the className class, call the method () function of the class, and call the onlyMethod () method at the same time. The output is normal and no error occurs .)

Step 3: directly call the Function

OnlyMethod ();

Note: The onlyMethod () function in the lib. php file is called directly without an instantiation class.
Output:
Fatal error: Call to undefined function onlyMethod () in '... (Omitted path )'

Step 4: instantiate the className class and then directly call

$ Class = new className ();
OnlyMethod ();

Output: method only

The above four steps show that if the loaded file contains a function, you must instantiate the class. Otherwise, an exception occurs. Call to undefined function is incorrect, pay attention to the specific usage.

Participant: spl_autoload_register

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.