ホームページ  >  記事  >  php教程  >  PHP の基本の自動ロード

PHP の基本の自動ロード

WBOY
WBOYオリジナル
2016-06-21 08:48:321009ブラウズ

PHP の自動ロード メカニズムは非常に重要です。ここでは 2 つの小さな演習を示します。

元の記事、転載する場合はその旨を明記してください: http://www.cnblogs.com/phpgcs

ファイル構造は次のとおりです。自動ロードを実現するには 2 つの方法があります

1、カスタム関数

2、spl_autoload_register()

liuyuan@ebuinfo:/var/www/phpgcs/php_autoload$ ll ./*

-rw-rw-r-- 1 liuyuan liuyuan 800 2月 19 日 11:39 ./func_autoload.php

-rw-rw-r-- 1 liuyuan liuyuan 906 2月 19 日 11:28 ./spl_autoload.php

./include:

合計 16

drwxrwxr-x 2 liuyuan liuyuan 4096 2月 19 日 11:42 ./

drwxrwxr-x 3 liuyuan liuyuan 4096 2月 19 日 11:43 ../

-rw-rw-r-- 1 liuyuan liuyuan 142 2月19日 11:42 aClass.php

-rw-rw-r-- 1 liuyuan liuyuan 143 2月19日 11:42 bClass.php

まずカスタム関数メソッドを見てみましょう:

define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '');

print_r(get_include_files());

EOL をエコー;

print get_include_path();

EOL をエコー;

//set_include_path(get_include_path().PATH_SEPARATOR.'/var/www/ly_php/php_spl/include/');

//set_include_path(dirname(__FILE__).'/include');

//set_include_path(dirname(__FILE__).'/include/');

関数 __autoload($className){

$filename = './include/'.$className.'.php';

//$filename = './include/'.$className.'.php';

//$filename = '/var/www/ly_php/php_spl/include/'.$className.'.php';

if(file_exists($filename)){

include_once $filename;

}その他{

exit('ファイルなし');

}

}

$a = new aClass();

$b = new bClass();

print_r(get_include_files());

?>

実行結果は次のとおりです:

+ コードを表示

2 番目の方法:

クラス myLoader{

パブリック静的関数 autoload($className){

$filename = './include/'.$className.'.php';

if(file_exists($filename)){

include_once $filename;

}その他{

exit('ファイルなし');

}

}

}

define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '
');

spl_autoload_register(array('myLoader', 'autoload'));

/**

autoload_func 関数ポインタがすでに spl_autoload メソッドを指しているため、spl_autoload_register の後に *__autoload メソッドは無効になります

* 次のメソッドを通じて、_autoload メソッドを autoload_functions リストに追加できます

*/

//spl_autoload_register( '__autoload' );

error_reporting(E_ALL^E_NOTICE^E_WARNING^E_ERROR);

error_reporting(E_NOTICE E_WARNING);

$a = new aClass();

print_r(get_include_files());

EOL をエコー;

$b = new bClass();

EOL をエコー;

?>



声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。