php 判断类存在,PHP怎么判断类是否存在

PHP怎么判断类是否存在

发布时间:2020-06-24 14:40:43

来源:亿速云

阅读:100

作者:Leah

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值