溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP怎么判斷類(lèi)是否存在

發(fā)布時(shí)間:2020-06-24 14:40:43 來(lái)源:億速云 閱讀:204 作者:Leah 欄目:編程語(yǔ)言

PHP怎么判斷類(lèi)是否存在?針對(duì)這個(gè)問(wèn)題,這篇文章給出了相對(duì)應(yīng)的分析和解答,希望能幫助更多想解決這個(gè)問(wèn)題的朋友找到更加簡(jiǎn)單易行的辦法。

在PHP中可以使用“class_exists()”函數(shù)檢測(cè)類(lèi)是否存,該函數(shù)的作用是檢查類(lèi)是否已定義,其用法為“class_exists($class_name)”,其參數(shù)“$class_name”代表要檢測(cè)的類(lèi)名。

示例代碼

<?php
// 使用前檢查類(lèi)是否存在
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.
*/
?>

關(guān)于PHP判斷類(lèi)是否存在的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI