• 技术文章 >后端开发 >PHP问题

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

    GuanhuiGuanhui2020-06-24 09:59:48原创805

    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检测类是否存在方法是什么?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:php
    上一篇:PHP如何替换指定字符? 下一篇:PHP如何结合AJAX删除数据?
    大前端线上培训班

    相关文章推荐

    • php基础学习之数组操作符• php基础语法规则梳理• php基础的语法规则• php基础知识考察点之正则表达式• php基础培训哪家好

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网