php之class_exists慎用


今天在網上查看class_exists方法(http://php.net/manual/en/function.class-exists.php)的用法的時候,發現class_exists方法的定義如下:
bool class_exists ( string $class_name [, bool $autoload = true ] );

它是有兩個參數的,我們平時用這個方法的時候大都只給了第一個參數,第二個參數的默認值是默認為true,而關於第二個參數的解釋是:
autoload
Whether or not to call __autoload by default.

所以當我們不設置第二個參數時,會去調用__autoload方法去加載類,
眾所周知__autoload方法的機制,它可能會對磁盤進行大量的I/O操作,嚴重影響效率,所以大家在用這個方法的時候可以用如下兩種方法解決:

NO1:把第二個參數設置為false
NO2:

To find out whether a class can be autoloaded, you can use autoload in this way:

<?php
//Define autoloader
function __autoload($className) {
    if (file_exists($className . '.php')) require $className . '.php';
    else throw new Exception('Class "' . $className . '" could not be autoloaded'); 
}

function canClassBeAutloaded($className) {
    try {
        class_exists($className);
        return true;
    }
    catch (Exception $e) {
        return false;
    }
}
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM