この関数を理解する前に、別の関数 __autoload を見てみましょう。
1. __autoload
これは、PHP5 で未定義のクラスをインスタンス化すると、この関数がトリガーされます。次の例を見てください:
<?php
PRINTIT
{
function __autoload( $class |
$file = $class . '.class.php' ; |
if ( is_file ( $file function |
doPrint()
{
运行index.php后正常输出hello world。在index.php中,由于没有包含printit.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时printit.class.php就被引进来了。
在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
二、spl_autoload_register()
再看spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:
function loadprint( $class
|
エコー
'こんにちは
世界
$file = $class . '.class.php' ; |
spl_autoload_register( 'loadprint' ); |
🎜🎜🎜🎜🎜🎜🎜🎜index.php 🎜🎜🎜🎜🎜🎜 🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜<?🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜関数🎜 🎜__autoload(🎜🎜$class🎜🎜)
{🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$file🎜🎜=🎜🎜$class🎜🎜'.class.php'🎜🎜; 🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜 🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜)
) { 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜}🎜🎜🎜🎜🎜🎜🎜 } 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜= 🎜🎜new🎜 🎜PRINTIT();🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜 🎜$obj🎜🎜->doPrint();🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜?>🎜🎜🎜🎜🎜🎜🎜 🎜🎜index.phpを実行すると、正常にhello worldが出力されます。 Index.php では、printit.class.php が含まれていないため、printit をインスタンス化する際に、自動的に __autoload 関数が呼び出されます。このとき、パラメータ $class の値は、printit.class.php が導入されます。 。 🎜🎜この方法はオブジェクト指向でよく使用され、多くの参照ファイルの作成を回避し、システム全体をより柔軟にすることができます。 🎜🎜2. spl_autoload_register() 🎜🎜 spl_autoload_register() をもう一度見てください。簡単な例を見てみましょう。 🎜🎜🎜🎜< ?🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜function🎜 🎜loadprint(🎜🎜$class🎜🎜)
{🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$file🎜🎜=🎜🎜$class🎜🎜'.class.php'🎜🎜; 🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜 🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜))
{ 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜🎜🎜🎜🎜🎜} 🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜spl_autoload_register(🎜) 🎜'ロードプリント'🎜🎜); 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜$obj🎜🎜= 🎜🎜新しい🎜 🎜PRINTIT();🎜🎜🎜🎜🎜
将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。
spl_autoload_register() 调用静态方法
public static function loadprint( $class ?> |
__autoload をloadprint 関数に置き換えます。ただし、loadprint は __autoload のように自動的にトリガーされません。この時点では、未定義のクラスが見つかったときに spl_autoload_register() が機能します。 spl_autoload_register() は静的メソッド $file = $class . '.class.php' ; |
を呼び出します。
クラス array ( 'test' , 'loadprint' テスト
{
|
function
loadprint(
=$class
'.class.php'
; 🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜 🎜if🎜🎜(🎜🎜is_file🎜🎜(🎜🎜$file🎜🎜))
{ 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜require_once🎜🎜(🎜🎜$file🎜🎜); 🎜🎜🎜🎜🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜}🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜} 🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜spl_autoload_register(
🎜🎜array🎜🎜(🎜🎜'test'🎜🎜,🎜🎜'loadprint'🎜🎜)
);🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜//別の書き方: spl_autoload_register( "test::loadprint"
); 🎜PRINTIT();🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜🎜 $obj🎜🎜->doPrint();🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜🎜🎜?>🎜🎜🎜🎜🎜 🎜🎜🎜
🎜
上記では、関連する側面も含めて spl_autoload_register 関数の詳細な説明を紹介しましたが、PHP チュートリアルに興味のある友人に役立つことを願っています。 🎜
🎜
🎜