久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

      怎樣使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)?

      在之前的文章中給大家?guī)砹恕禤HP中怎樣去判斷對象是否屬于一個類?》,其中詳細(xì)介紹了在PHP中應(yīng)該增陽區(qū)判斷一個對象是否屬于一個類的相關(guān)知識,本篇文章我們來看一下PHP中的自動加載機(jī)制。希望對大家有幫助!

      怎樣使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)?

      在日常開發(fā)使用時,我們面向?qū)ο蟪绦蛟O(shè)計的基本思想是,通常情況下習(xí)慣為每個類都創(chuàng)建一個單獨的PHP源文件,這樣的話為后來的維護(hù)提供便利,同時也很容易對類進(jìn)行復(fù)用。

      在PHP中可以通過spl_autoload_register() __autoload() 函數(shù)來實現(xiàn)類的自動加載功能,這樣可以節(jié)省我們的編程時間和精力。那接下來我們就分別來介紹一下這兩個函數(shù)吧。

      __autoload()函數(shù)

      __autoload()函數(shù)準(zhǔn)確來說它是魔術(shù)方法,我們在《五分鐘帶你了解PHP中的魔術(shù)方法(實例詳解)》中詳細(xì)的介紹了一些常用的魔術(shù)方法,其中講到,它是自動調(diào)用的,也就是需要早特定條件下才會調(diào)用函數(shù)。

      當(dāng)我們 new 一個類時,如果當(dāng)前源文件中找不到這個類,PHP 則會自動調(diào)用 __autoload() 函數(shù),并將類名傳遞給 __autoload() 函數(shù)。這就是__autoload()函數(shù)調(diào)用的特定條件。它的語法格式如下:

      function __autoload($class){     // 方法體 }

      其中我們需要注意的是:

      • $class 為要加載的類名。

      • __autoload() 函數(shù)在當(dāng)前源文件中只能定義一次。

      • 想要使用 __autoload() 函數(shù)自動加載類文件,類文件的名稱需要與類名相同,另外一個類文件中只能定義一個類。

      接下來我們通過示例來看一下__autoload() 函數(shù)的使用,示例如下:

      <?php     function __autoload($class){         $file = './'.$class.'.php';         include_once($file);     }     $obj = new Demo(); ?>

      運(yùn)行上面的代碼,會自動加載同目錄下的 Demo.php 文件,Demo.php 中的代碼如下所示:

      <?php     class Demo{     } ?>

      其中我們需要注意的是:__autoload() 函數(shù)自 PHP7.2.0 起已被棄用,可以使用 spl_autoload_register() 函數(shù)代替。

      spl_autoload_register() 函數(shù)

      spl_autoload_register()函數(shù)可以指定一個函數(shù)來替代__autoload()函數(shù)的功能,

      spl_autoload_register([$autoload_function [, $throw = true [, $prepend = false ]]])

      其中需要注意的是:

      • $autoload_function:要替代 __autoload() 函數(shù)的函數(shù)名稱,也可以是一個匿名函數(shù)。如果沒有提供任何參數(shù),則自動注冊 autoload 的默認(rèn)實現(xiàn)函數(shù) spl_autoload();

      • $throw:用來設(shè)置 $autoload_function 無法成功注冊時,spl_autoload_register() 函數(shù)是否拋出異常;

      • $prepend:如果是 true,則 spl_autoload_register() 函數(shù)會添加 $autoload_function 函數(shù)到隊列之首,否則添加到隊列尾部。

      接下來我們通過示例來看一下,示例如下:

      <?php     spl_autoload_register('loadClass');     function loadClass($class){         $file = './'.$class.'.php';         include_once($file);     }     $obj = new Demo(); ?>

      上述示例中使用 spl_autoload_register() 函數(shù)指定另一個函數(shù)來替代 __autoload() 函數(shù)。

      大家如果感興趣的話,可以點擊《PHP視頻教程》進(jìn)行

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號