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
/**
* 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.
*/
?>
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
/**
* Set my include path here
*/
$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() {}
/**
* By registering the additional custom autoload function that does nothing
* class_exists() returns only boolean and does NOT throw an uncaught Exception
*/
?>
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!
class_exists
(PHP 4, PHP 5)
class_exists — Checks if the class has been defined
Beschreibung
bool class_exists
( string
$class_name
[, bool $autoload = true
] )Diese Funktion prüft ob eine bestimmte Klasse definiert wurde.
Parameter-Liste
-
class_name -
Der Klassenname. Groß- und Kleinschreibung wird bein Vergleich nicht beachtet.
-
autoload -
Gibt an ob __autoload genutzt werden soll. Vorgabewert ist
TRUE.
Rückgabewerte
Gibt TRUE zurück falls die Klasse class_name
definiert ist, sonst FALSE.
Changelog
| Version | Beschreibung |
|---|---|
| 5.0.2 |
Die Funktion liefert nun nicht mehr TRUE für Interfaces.
Nutzen Sie hierfür interface_exists().
|
| 5.0.0 |
Der autoload Parameter wurde hinzugefügt.
|
Beispiele
Beispiel #1 class_exists() Beispiel
<?php
// prüft vor Benutzung ob die gewünschte Klasse definiert ist
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
Beispiel #2 autoload Parameter Beispiel
<?php
function __autoload($class)
{
include($class . '.php');
// Prüft ob die includierte Datei die Klasse tatsächlich definiert
if (!class_exists($class, false)) {
trigger_error("Die Klasse $class kann nicht geladen werden", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
Siehe auch
- function_exists() - Falls die angegebene Funktion definiert ist, wird TRUE zurück gegeben
- interface_exists() - Prüft ob ein bestimmtes Interface definiert wurde
- get_declared_classes() - Ermittelt die Namen der definierten Klassen
toocoolone at gmail dot com
14-Feb-2012 06:47
Anonymous
07-Mar-2011 10:21
It might not be obvious to some, but whenever you reference a namespace in a string, each backslash must be escaped with another backslash because of how PHP handles strings.
<?php
class_exists('\\Zend_Registry'); // return true
?>
myb at mikebevz dot com
23-Sep-2010 06:50
I've got a problem, which I can't solve.
Let's assume that class Zend_Registry exists in global namespace.
---
namespace myNs;
class SomeClass {
public function MyFunc() {
class_exists('Zend_Registry'); // return false
class_exists('\Zend_Registry'); // return false
class_exists('::Zend_Registry'); // return false
}
}
---
How would I check for a class, which exists outside of myNs?
Klaus
28-Apr-2010 04:21
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.
azrael dot com at gmail dot com
11-Dec-2008 04:14
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());
?>
Anonymous
29-Nov-2008 10:27
If you planned to use utf-8 in classes or variables names, remember that locale has to be properly set firstly, e.g.
<?php
locale (LC_ALL, 'ru_RU.UTF-8');
?>
or it turn into errors.
Radek @ cz
05-May-2008 06:43
If you want to combat many class includes effectively, define your own autoloader function and spl_autoload_register() that autoloader.
richard at richard-sumilang dot com
27-Mar-2008 12:56
[ >= 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";
Frayja
01-Jun-2006 01:42
Like someone else pointed out class_exists() is case-INsensitive.
Using in_array() which is case-sensitive, the following function is a case-sensitive version of class_exists().
<?php
function class_exists_sensitive( $classname )
{
return ( class_exists( $classname ) && in_array( $classname, get_declared_classes() ) );
}
?>
06-Apr-2004 05:04
Just a note that at least PHP 4.3.1 seems to crash under some situations if you call class_exists($foo) where $foo is an array (that is, the calling code is incorrect but the error recovery is far from perfect).
anonymous at somewhere dot tld
17-Jul-2003 12:20
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
