7

次のような関数で必要なときにクラスファイルを動的にロードする方法について読みました。

function __autoload($className)
{
   include("classes/$className.class.php");
}

$obj = new DB();

DB.class.phpこれは、そのクラスの新しいインスタンスを作成すると自動的に読み込まれますが、これはグローバル関数であり、プロジェクトに持ち込む関数を持つライブラリはそれ__autoload()を台無しにするため、これを使用するのは悪いことです。上。

それで、誰かが解決策を知っていますか?おそらく、同じ効果を達成するための別の方法__autoload()ですか?適切な解決策が見つかるまで__autoload()、図書館などを持ち込むまで問題になり始めないので、使い続けます。

ありがとう。

4

6 に答える 6

11

次のコードを使用して、spl_autoload_registerが存在しない場合に劣化するように使用し、含める必要のある__autoloadを使用するライブラリも処理しました。

//check to see if there is an existing __autoload function from another library
if(!function_exists('__autoload')) {
    if(function_exists('spl_autoload_register')) {
        //we have SPL, so register the autoload function
        spl_autoload_register('my_autoload_function');      
    } else {
        //if there isn't, we don't need to worry about using the stack,
        //we can just register our own autoloader
        function __autoload($class_name) {
            my_autoload_function($class_name);
        }
    }

} else {
    //ok, so there is an existing __autoload function, we need to use a stack
    //if SPL is installed, we can use spl_autoload_register,
    //if there isn't, then we can't do anything about it, and
    //will have to die
    if(function_exists('spl_autoload_register')) {
        //we have SPL, so register both the
        //original __autoload from the external app,
        //because the original will get overwritten by the stack,
        //plus our own
        spl_autoload_register('__autoload');
        spl_autoload_register('my_autoload_function');      
    } else {
        exit;
    }

}

したがって、そのコードは既存の__autoload関数をチェックし、それをスタックに追加するだけでなく、独自の関数も追加します(spl_autoload_registerは通常の__autoloadの動作を無効にするため)。

于 2010-04-13T15:06:30.963 に答える
7

を使用spl_autoload_register()して、既存の__autoload()魔法をスタックに追加できます。

function my_autoload( $class ) {    
    include( $class . '.al.php' );
}
spl_autoload_register('my_autoload');

if( function_exists('__autoload') ) {
    spl_autoload_register('__autoload');
}                                                                                         

$f = new Foo;
于 2010-04-13T15:05:54.993 に答える
4

正しい方法は、を使用することspl_autoload_registerです。一部のサードパーティが導入した関数を保存する__autoloadには、その関数をオートローダースタックに配置することもできます。

if (function_exists('__autoload')) {
    spl_autoload_register('__autoload');
}
于 2010-04-13T15:05:59.620 に答える
3

__autoloadの代わりにspl_autoload_registerを使用してください。これにより、自動ロード機能をスタックに追加できるようになります。

于 2010-04-13T14:57:13.337 に答える
0

できる最善のことは、プログラミングしているサブシステムの自動ロードを担当する独自のオブジェクトを定義することです。

例えば:

class BasketAutoloader
{
  static public function register()
  {
    spl_autoload_register(array(new self, 'autoload'));
  }

  public function autoload($class)
  {
    require dirname(__FILE__).'/'.$class.'.php';
  }
}
于 2010-04-13T16:19:13.693 に答える
0

Zend_Loaderを使用できます。(Zend Frameworkが利用可能であると仮定します...)

于 2010-04-13T15:00:37.490 に答える