Section 12th-Automatic loading of classes-Classes and Objects in PHP5 [12]

Source: Internet
Author: User
Tags include lowercase php programming
object|php5| Loading | = This article is for Haohappy read <<core PHP programming>>
| = Notes from the chapter classes and objects
| = translation-oriented + personal experience
| = Please do not reprint to avoid any unnecessary trouble that may occur, thank you
| = Welcome to criticize, hope and all PHP enthusiasts to progress together!
+-------------------------------------------------------------------------------+
*/

Section 12th-Automatic loading of classes

When you try to use an undefined class, PHP reports a fatal error. The workaround is to add a class that can include a file with include. After all, you know which class to use. However, PHP provides automatic loading of classes, which can save programming time. When you try to use a class that PHP does not organize into, it looks for a __autoload global function. If this function is present, PHP calls it with a parameter, which is the name of the class.

Example 6.15 illustrates how __autoload is used. It assumes that each file in the current directory corresponds to a class. When the script tries to produce an instance of class user, PHP executes __autoload. The script assumes that the User class is defined in class_user.php. PHP returns the lowercase of the name, regardless of whether the call is uppercase or lowercase.

Listing 6.15 Class autoloading
<?php
Define AutoLoad function
function __autoload ($class)
{
Include ("Class_". Ucfirst ($class). ". php");
}

Use a class which must be autoloaded
$u = new User;
$u->name = "Leon";
$u->printname ();
?>


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.