PHP怎么判断类是否存在

发布时间:2020-06-24 14:40:43 作者:Leah
来源:亿速云 阅读:194

PHP怎么判断类是否存在?针对这个问题,这篇文章给出了相对应的分析和解答,希望能帮助更多想解决这个问题的朋友找到更加简单易行的办法。

在PHP中可以使用“class_exists()”函数检测类是否存,该函数的作用是检查类是否已定义,其用法为“class_exists($class_name)”,其参数“$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.
*/
?>

关于PHP判断类是否存在的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. php如何判断远程图片是否存在
  2. php如何判断数组下标是否存在

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:PHP+AJAX实现删除数据的方法

下一篇:在Anaconda中安装dlib库步骤

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》