首頁  >  文章  >  後端開發  >  幾個php中類別的自動載入的方法的實例詳解

幾個php中類別的自動載入的方法的實例詳解

伊谢尔伦
伊谢尔伦原創
2017-07-01 10:03:011531瀏覽

本篇文章主要介紹了PHP中類別的自動載入的方法。類別的自動載入是指在外面的頁面中並不需要去「引入」類別文件,但是程式會在需要的時候動態載入需要的類別文件。

類別的自動載入是指,在外面的頁面中,並不需要去「引入」類別文件,但是程式會在需要的時候動態載入需要的類別文件。

方法1:使用autoload魔術函數

#當程式需要某個類別時,就會去呼叫該函數,該函數我們需要自己去定義並在其中寫好載入類別文件的通用語句。

<?php
    //需要类是自动调用,而且会传进来一个类名,这个案例的文件名为21A.class.php,类名为A
     function autoload($className){
      require "./21".$className.".class.php";
    }
    $o1 = new A();
    $o1->v1 = 10;
    echo "<br/>v1:".$o1->v1;
  ?>

方法2:使用spl_autoload_register函數

此函數的作用是生命多個可以用來代替autoload函數作用的函數,文法如下:spl_autoload_regist("函數名稱1");如果用spl_autoload_register,autoload就失效了。

<?php
    //注册两个用于自动加载的函数名
    spl_autoload_register(&#39;auto1&#39;);
    spl_autoload_register(&#39;auto2&#39;);
    function auto1($className){
      $file = "./21".$className.".class.php";
      if(file_exists($file)){
        require "./21".$className.".class.php";
      }
    }
    function auto1($className){
      $file = "./22".$className.".class.php";
      if(file_exists($file)){
        require "./22".$className.".class.php";
      }
    }
    //如果需要一个雷,但这个页面还没有记载,就会依次调用auto1和auto2,知道找到该类文件并加载
  ?>

再多一個例子:

這裡autoload 可相容以下格式:

Cache_File_Json 
class_xxx.php 
xxx.class.php 
#  xxx. php

php程式碼如下:

function autoload($className){
 $dirs=explode(&#39;_&#39;,$className);
 $fileName=array_pop($dirs);
 //print_r($dirs);
 $filePath=$fileName;
 if(is_array($dirs) && (count($dirs) > 0)){
  //echo &#39;\n---\n&#39;; print_r($dirs);
  $dirPath=&#39;&#39;;
  foreach ($dirs as $dir){
   if($dir){
    $dirPath.=strtolower($dir).DIRECTORY_SEPARATOR;
   }
  }
  $filePath=$dirPath.$fileName.&#39;.php&#39;;
 }else {
  if( file_exists(&#39;class_&#39;.$fileName.&#39;.php&#39;)){
   $filePath=&#39;class_&#39;.$fileName.&#39;.php&#39;;
  }else {
   if( file_exists($fileName.&#39;.class.php&#39;)){
    $filePath=$fileName.&#39;.class.php&#39;;
   } else {
    $filePath=$fileName.&#39;.php&#39;;
   }
  }
 }
 //var_dump($filePath);
 require $filePath;
}

以上是幾個php中類別的自動載入的方法的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn