©
本文档使用 PHP中文网手册 发布
(PHP 4, PHP 5, PHP 7)
class_exists — 检查类是否已定义
$class_name
[, bool $autoload
= true
] )检查指定的类是否已定义。
class_name
类名。名字的匹配是大小写不敏感的。
autoload
是否默认调用 __autoload。
如果由 class_name
所指的类已经定义,此函数返回
TRUE
,否则返回 FALSE
。
版本 | 说明 |
---|---|
5.0.2 |
不再为已定义的 interface 返回 TRUE 。请使用
interface_exists() 。
|
5.0.0 |
增加参数 autoload 。
|
Example #1 class_exists() 例子
<?php
// 使用前检查类是否存在
if ( class_exists ( 'MyClass' )) {
$myclass = new MyClass ();
}
?>
Example #2 autoload
parameter 例子
<?php
function __autoload ( $class )
{
include( $class . '.php' );
// Check to see whether the include declared the class
if (! class_exists ( $class , false )) {
trigger_error ( "Unable to load class: $class " , E_USER_WARNING );
}
}
if ( class_exists ( 'MyClass' )) {
$myclass = new MyClass ();
}
?>
[#1] rn at alpha9marketing dot com [2014-04-06 17:55:57]
Beware: class_exists is case-INsensitive, as is class instantiation.
php > var_dump(class_exists("DomNode"));
bool(true)
php > var_dump(class_exists("DOMNode"));
bool(true)
php > var_dump(class_exists("DOMNodE"));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) "DOMNode"
(tested with PHP 5.5.10 on Linux)
This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
[#2] spam at wikicms dot org [2013-12-09 14:43:23]
Hi guys!
Be careful and don't forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
<?php
class Second {}
?>
file index.php
<?php
class First
{
function first($class, $bool) {
spl_autoload_register( function($class) {
require strtolower($class) . '.php';
});
echo class_exists($class, $bool)?'Exist!!!!':'Not exist!';
}
}
new First($class = 'Second', $bool = true); //Exist!!!!
new First($class = 'Second', $bool = false); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..
[#3] giunta dot gaetano at gmail dot com [2013-10-31 17:28:39]
If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used
use a\namespaced\classname as coolclass;
class_exists( 'coolclass' ) => false
[#4] toocoolone at gmail dot com [2012-02-14 06:47:11]
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.
<?php
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
try {
if( ! file_exists( 'myfile.php' ) ) {
throw new MyException('Doh!');
}
include( 'myfile.php' );
}
catch( MyException $e ) {
echo $e->getMessage();
}
$classname = 'NonExistentClass';
try {
if( ! class_exists( $classname ) ) {
throw new MyException('Double Doh!');
}
$var = new $classname();
}
catch( MyException $e ) {
echo $e->getMessage();
}
?>
By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.
<?php
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
?>
Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
[#5] Klaus [2010-04-28 04:21:39]
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.
Apparently, the internal list of declared classes is only updated after the autoload function is completed.
[#6] azrael dot com at gmail dot com [2008-12-11 16:14:18]
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.
Use instead
<?php
in_array($class_name, get_declared_classes());
?>
[#7] Radek @ cz [2008-05-05 18:43:05]
If you want to combat many class includes effectively, define your own autoloader function and spl_autoload_register() that autoloader.
[#8] richard at richard-sumilang dot com [2008-03-27 00:56:55]
[ >= PHP 5.3]
If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:
echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
[#9] anonymous at somewhere dot tld [2003-07-17 12:20:31]
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that
<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
while (($file = readdir($dh)) !== false) {
if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
// include and create the class
require_once($this->MODULE_PATH."/".$file);
$modules[] = new $matches[1]();
}
}
} else {
exit;
}
?>
//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code