《PHP實(shí)戰(zhàn):深入理解PHP類的自動(dòng)載入機(jī)制》要點(diǎn):
本文介紹了PHP實(shí)戰(zhàn):深入理解PHP類的自動(dòng)載入機(jī)制,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)戰(zhàn)php的自動(dòng)加載:
PHP實(shí)戰(zhàn)在php5以前,我們要用某個(gè)類或類的方法,那必須include或者require,之后才能使用,每次用一個(gè)類,都需要寫一條include,麻煩
PHP實(shí)戰(zhàn)php作者想簡單點(diǎn),最好能引用一個(gè)類時(shí),如果當(dāng)前沒有include進(jìn)來,系統(tǒng)能自動(dòng)去找到該類,自動(dòng)引進(jìn)~
PHP實(shí)戰(zhàn)于是:__autoload()函數(shù)應(yīng)運(yùn)而生.
PHP實(shí)戰(zhàn)通常放在應(yīng)用程序入口類里面,比如discuz中,放在class_core.php中.
PHP實(shí)戰(zhàn)先講淺顯的例子:
PHP實(shí)戰(zhàn)第一種情況:文件A.php中內(nèi)容如下
PHP實(shí)戰(zhàn)
<?php
class A{
public function __construct(){
echo 'fff';
}
}
?>
PHP實(shí)戰(zhàn)文件C.php 中內(nèi)容如下:
PHP實(shí)戰(zhàn)
<?php
function __autoload($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
$a = new A(); //這邊會(huì)自動(dòng)調(diào)用__autoload,引入A.php文件
?>
PHP實(shí)戰(zhàn)第二種情況:有時(shí)我希望能自定義autoload,并且希望起一個(gè)更酷的名字loader,則C.php改為如下:
PHP實(shí)戰(zhàn)
<?php
function loader($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register('loader'); //注冊一個(gè)自動(dòng)加載方法,覆蓋原有的__autoload
$a = new A();
?>
PHP實(shí)戰(zhàn)第三種情況:我希望高大上一點(diǎn),用一個(gè)類來管理自動(dòng)加載
PHP實(shí)戰(zhàn)
<?php
class Loader
{
public static function loadClass($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
}
spl_autoload_register(array('Loader', 'loadClass'));
$a = new A();
?>
PHP實(shí)戰(zhàn)當(dāng)前為最佳形式.
PHP實(shí)戰(zhàn)通常我們將spl_autoload_register(*)放在入口腳本,即一開始就引用進(jìn)來.比如下面discuz的做法.
PHP實(shí)戰(zhàn)
if(function_exist('spl_autoload_register')){
spl_autoload_register(array('core','autoload')); //如果是php5以上,存在注冊函數(shù),則注冊自己寫的core類中的autoload為自動(dòng)加載函數(shù)
}else{
function __autoload($class){ //如果不是,則重寫php原生函數(shù)__autoload函數(shù),讓其調(diào)用自己的core中函數(shù).
return core::autoload($class);
}
}
PHP實(shí)戰(zhàn)這段扔在入口文件最前面,自然是極好的~
PHP實(shí)戰(zhàn)以上這篇深入理解PHP類的自動(dòng)載入機(jī)制就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持維易PHP.
轉(zhuǎn)載請(qǐng)注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/3802.html