PHP Tutorial: AutoLoad Auto Load Class

Source: Internet
Author: User
Tags autoload php file php error php tutorial

when developing a system using the OO pattern in PHP, it is often customary to store implementations of each class in a separate file, which makes it easy to reuse classes and facilitates future maintenance. 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 in.

test.class.php








?>

load.php

Code to copy the code as follows
















__autoload ()
In the actual project, it is impossible to write all the classes in a PHP file, when you need to invoke another file in a PHP file declared class, you need to introduce this file through the include. However, sometimes, in a large number of projects, to all the required class files included, a big trouble is to have to write at the beginning of each class file a long list of included files. Can we import the PHP file of this class when we use the class?

To do this, PHP provides the __autoload () method, which is invoked automatically when an attempt is made to use a class that has not yet been defined. By calling this function, the script engine had the last chance to load the class that was required before the PHP error failed.

The __autoload () method receives a parameter, is the class name that wants to load, so this time need class name and filename corresponding, if person.php, corresponding class name is Pserson.

Let's look at a complete example
























After defining two test classes, we will write a PHP run program file containing the __autoload () method as follows:









}


$newobj = new ClassB ();

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.