ホームページ  >  記事  >  バックエンド開発  >  PHPでクラスが存在するかどうかを検出する方法は何ですか?

PHPでクラスが存在するかどうかを検出する方法は何ですか?

Guanhui
Guanhuiオリジナル
2020-06-24 09:59:482716ブラウズ

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チュートリアル

以上がPHPでクラスが存在するかどうかを検出する方法は何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。