Class library a...LOGIN

Class library automatic loading

As the business becomes more and more complex, a script will need to include or require more and more class files,

At this time, you need to use the __autoload() method to automatically load the class file when instantiating the object

1, the use of __antoload()

Create a new init.php file with the following code:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 3:39
 */
header('content-type:text/html;charset=utf8');
function __autoload($className){
    //自动加载类名为className,文件名为./$className.class.php的文件
    require "./$className.class.php";
}

2, test

Create new student class and teacher class

Student.class.php code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 3:41
 */
class Student{
    public function __construct()
    {
        echo "学生类已加载";
    }
}

Teacher.class.php code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 3:41
 */
class Teacher{
    public function __construct()
    {
        echo "老师类已加载";
    }
}

Create the index.php file to test whether the corresponding class file needs to be introduced at the same time to load the corresponding constructor

The code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/3 0003
 * Time: 下午 3:43
 */
require './init.php';
$student=new Student();
echo "<br>";
$teacher=new Teacher();

The effect of running the index.php file in the browser is as follows:

微信图片_20180303155335.png

<?php echo "自动加载的使用";
submitReset Code
ChapterCourseware