Heim  >  Artikel  >  类库下载  >  PHP类的自动载入机制

PHP类的自动载入机制

高洛峰
高洛峰Original
2016-10-10 10:08:271376Durchsuche

php的自动加载:

在php5以前,我们要用某个类或类的方法,那必须include或者require,之后才能使用,每次用一个类,都需要写一条include,麻烦

php作者想简单点,最好能引用一个类时,如果当前没有include进来,系统能自动去找到该类,自动引进~

于是:__autoload()函数应运而生。

通常放在应用程序入口类里面,比如discuz中,放在class_core.php中。

先讲浅显的例子:

第一种情况:文件A.php中内容如下

<?php
class A{
  public function __construct(){
         echo &#39;fff&#39;;
  }
}
?>
文件C.php 中内容如下:
<?php   
function __autoload($class)   
{   
$file = $class . &#39;.php&#39;;   
if (is_file($file)) {   
require_once($file);   
}   
}   

$a = new A(); //这边会自动调用__autoload,引入A.php文件
?>

第二种情况:有时我希望能自定义autoload,并且希望起一个更酷的名字loader,则C.php改为如下:

<?php
function loader($class)
{
$file = $class . &#39;.php&#39;;
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register(&#39;loader&#39;); //注册一个自动加载方法,覆盖原有的__autoload
$a = new A();
?>

第三种情况:我希望高大上一点,用一个类来管理自动加载

<?php   
class Loader   
{   
public static function loadClass($class)   
{   
$file = $class . &#39;.php&#39;;   
if (is_file($file)) {   
require_once($file);   
}   
}   
}   

spl_autoload_register(array(&#39;Loader&#39;, &#39;loadClass&#39;));   

$a = new A();
?>

当前为最佳形式。

通常我们将spl_autoload_register(*)放在入口脚本,即一开始就引用进来。比如下面discuz的做法。

if(function_exist(&#39;spl_autoload_register&#39;)){
  spl_autoload_register(array(&#39;core&#39;,&#39;autoload&#39;));  //如果是php5以上,存在注册函数,则注册自己写的core类中的autoload为自动加载函数
}else{
  function __autoload($class){         //如果不是,则重写php原生函数__autoload函数,让其调用自己的core中函数。
    return core::autoload($class);
  }
}

这段扔在入口文件最前面,自然是极好的~

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

In Verbindung stehende Artikel

Mehr sehen