Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP检测类是否存在方法是什么?

PHP检测类是否存在方法是什么?

Guanhui
Guanhuiasal
2020-06-24 09:59:482716semak imbas

PHP检测类是否存在方法是什么?

PHP检测类是否存在方法是什么?

在PHP中可以使用“class_exists()”函数检测类是否存,该函数的作用是检查类是否已定义,其用法为“class_exists($class_name)”,其参数“$class_name”代表要检测的类名。

推荐视频教程:《PHP编程从入门到精通(学习路线)

示例代码

<?php
// 使用前检查类是否存在
if (class_exists(&#39;MyClass&#39;)) {
    $myclass = new MyClass();
}

?>
<?php
/**
* Set my include path here
*/
$include_path = array( &#39;/include/this/dir&#39;, &#39;/include/this/one/too&#39; );
set_include_path( $include_path );
spl_autoload_register();
/**
* Assuming I have my own custom exception handler (MyException) let&#39;s
* try to see if a file exists.
*/
try {
    if( ! file_exists( &#39;myfile.php&#39; ) ) {
        throw new MyException(&#39;Doh!&#39;);
    }
    include( &#39;myfile.php&#39; );
}
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 = &#39;NonExistentClass&#39;;
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException(&#39;Double Doh!&#39;);
    }
    $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&#39;ve got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

推荐教程:《PHP教程

Atas ialah kandungan terperinci PHP检测类是否存在方法是什么?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn