Home  >  Article  >  Backend Development  >  What is the method to detect whether a class exists in PHP?

What is the method to detect whether a class exists in PHP?

Guanhui
GuanhuiOriginal
2020-06-24 09:59:482758browse

What is the method to detect whether a class exists in PHP?

#What is the method in PHP to detect whether a class exists?

In PHP, you can use the "class_exists()" function to check whether the class exists. The function of this function is to check whether the class has been defined. Its usage is "class_exists($class_name)", and its parameter " $class_name" represents the class name to be detected.

Recommended video tutorial: "PHP Programming from Beginner to Master (Learning Route)"

Sample code

<?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.
*/
?>

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of What is the method to detect whether a class exists in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn