php 判断类存在,PHP怎么判断类是否存在
PHP怎么判斷類是否存在
發(fā)布時間:2020-06-24 14:40:43
來源:億速云
閱讀:100
作者:Leah
PHP怎么判斷類是否存在?針對這個問題,這篇文章給出了相對應(yīng)的分析和解答,希望能幫助更多想解決這個問題的朋友找到更加簡單易行的辦法。
在PHP中可以使用“class_exists()”函數(shù)檢測類是否存,該函數(shù)的作用是檢查類是否已定義,其用法為“class_exists($class_name)”,其參數(shù)“$class_name”代表要檢測的類名。
示例代碼<?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.
*/
?>
關(guān)于PHP判斷類是否存在的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
總結(jié)
以上是生活随笔為你收集整理的php 判断类存在,PHP怎么判断类是否存在的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php如何删除单个数组,如何在php中使
- 下一篇: envi读取格式ang 还是mtl,La