PHP __autoload()函数

来源:互联网 发布:描述欧几里德算法 编辑:程序博客网 时间:2024/05/16 19:20

当我们在写一个系统时,很多开发者喜欢每写一个类,就新建一个.php文件。当然也有人喜欢将类写在同一个文件下。但当系统太大,太繁琐时。写在同一个文件里,是行不通的。


当在一个PHP文件中需要调用另一个文件中声明的类时,就需要通过include把 这个文件引入。不过有的时候,在文件众多的项目中,要一一将所需类的文件都include进来,是一个很让人头疼的事,所以我们能不能在用到什么类的时 候,再把这个类所在的php文件导入呢?这就是我们这里我们要讲的自动加载类。


我想通过下面这些代码进行一次测试,我将两个不同的类写在两个不同的.php文件下。它们分别是:index2.php与index3.php。但它们在统一目录下:

For example:

index3.php

    class  test{        private $var1;        private $var2;        private $var3;        public function __construct($var1,$var2,$var3){            $this->var1=$var1;            $this->var2=$var2;            $this->var3=$var3;        }        public function hello(){            return "var1:".$this->var1." "."var2:".$this->var2." "."var3:".$this->var3;        }    }   

下面我想通过index2.php来访问index3.php中的内容;

index2.php

访问方法一:

//为了防止输出乱码header("Content-type:text/html;charset=utf-8");function  __autoload($classname){    require $classname.".php";}__autoload("index3");$T=new test("小红","小明","小樱");echo $T->hello();
output:   var1:小红 var2:小明 var3:小樱

访问方法二:

    class index2{        private $name;        private $age;        private $sex;        public function __construct($name,$age,$sex){            $this->name=$name;            $this->age=$age;            $this->sex=$sex;        }        public function information(){            return "我的名字是:".$this->name."我的年龄是:".$this->age."我的性别是:".$this->sex."<br>";        }        public function __autoload($classname){            return require $classname.'.php';        }    }    $i=new index2("小倩", 25, "女");    echo $i->information();    $i->__autoload("index3");    $T=new test("小红","小明","小樱");    echo $T->hello();
output:  我的名字是:小倩我的年龄是:25我的性别是:女var1:小红 var2:小明 var3:小樱

参考目录:http://www.php-note.com/article/detail/44

0 0
原创粉丝点击