PHP檢測類是否存在方法是什麼?
在PHP中可以使用「class_exists()」函數檢測類是否存,該函數的作用是檢查類是否已定義,其用法為「class_exists($class_name)」,其引數「$class_name」代表要檢測的類名。
推薦視訊教學:《PHP程式設計從入門到精通(學習路線)》
範例程式碼
<?php // 使用前檢查類是否存在 if (class_exists('MyClass')) { $myclass = new MyClass(); } ?>
<?php /** * Set my include path here */ $include_path = array( '/include/this/dir', '/include/this/one/too' ); set_include_path( $include_path ); spl_autoload_register(); /** * Assuming I have my own custom exception handler (MyException) let's * try to see if a file exists. */ try { if( ! file_exists( 'myfile.php' ) ) { throw new MyException('Doh!'); } include( 'myfile.php' ); } catch( MyException $e ) { echo $e->getMessage(); } /** * The above code either includes myfile.php or throws the new MyException * as expected. No problem right? The same should be true of class_exists(), * right? So then... */ $classname = 'NonExistentClass'; try { if( ! class_exists( $classname ) ) { throw new MyException('Double Doh!'); } $var = new $classname(); } catch( MyException $e ) { echo $e->getMessage(); } /** * Should throw a new instance of MyException. But instead I get an * uncaught LogicException blah blah blah for the default Exception * class AND MyException. I only catch MyException so we've got on * uncaught resulting in the dreaded LogicException error. */ ?>
推薦教學:《PHP教學》
以上就是PHP檢測類是否存在方法是什麼?的詳細內容,更多請關注TW511.COM其它相關文章!