Php узнать существует ли класс

PHP class_exists

Summary: in this tutorial, you’ll learn how to use the PHP class_exists() function to check if a class exists or not.

Introduction to the PHP class_exists() function

The class_exists() function accepts a class name and returns true if the class exists or false otherwise.

class_exists(string $class, bool $autoload = true): boolCode language: PHP (php)

The class_exists() function has two parameters:

  • $class specifies the name of the class to check.
  • $autoload determines whether to call spl_autoload_register() by default.

Note that the class_exists() is case-insensitive. It means that if you have a class with the name User , the class_exists(‘user’) will return true.

The class_exists() function is often used in model-view-controller (MVC) frameworks to load the controller class based on a route.

PHP class_exists() function examples

Let’s take some examples of using the class_exists() function.

1) Using the PHP class_exists() function to check if a class exists

First, define a class User in the User.php file:

 class User  Code language: PHP (php)

Second, require the User.php file in the index.php and use the class_exists() function to check if the User class exists:

 require 'User.php'; if (class_exists('User')) < echo 'The class User exists'; > else < echo 'The class User does not exist'; >Code language: PHP (php)

Since the require construct loads the User.php class, you’ll see the following output:

The class User existsCode language: PHP (php)

If you comment the require statement and execute the script again, you’ll see the following output:

The class User does not existCode language: PHP (php)

2) Using the PHP class_exists() function to check if a namedspaced clas exists

First, add the App namespace to the User class:

 namespace App; class User  Code language: PHP (php)

Second, execute the following script:

 require 'User.php'; if (class_exists('User')) < echo 'The class User exists'; > else < echo 'The class User does not exist'; >Code language: PHP (php)

… you’ll see the following output:

The class User does not existCode language: PHP (php)

The reason is that the User class is namespaced. The class name is App\User , not User .

To fix this, you can use the fully-qualified class name like this:

 require 'User.php'; if (class_exists('App\User')) < echo 'The class App\User exists'; > else < echo 'The class Appp\User does not exist'; >Code language: PHP (php)

If you execute the script again, you’ll see this output:

The class App\User existsCode language: PHP (php)

3) Using the class_exists() with the class alias

The class_exists() doesn’t work with the aliased class name. For example:

require 'User.php'; use App\User as Account; var_dump(class_exists('Account')); // bool(false) Code language: PHP (php)

4) Using the PHP class_exists() with spl_autoload_register() example

First, define the User class in the User.php file in the app folder as follows:

 namespace App; class User < public function avartar(): string < return 'default'; > >Code language: PHP (php)

Second, create an index.php file in the root folder and place the following code:

 spl_autoload_register(function ($class) < echo 'Loading the class ' . $class . '
'
; require $class . '.php'; >); class_exists('App\User'); echo 'Create a new user' . '
'
; $user = new App\User(); echo $user->avartar();
Code language: PHP (php)
Loading the class App\User Create a new user default"mode":"full","isActive":false>Code language: PHP (php)

First, the class_exists() function checks whether the App\User class exists and call the spl_autoload_register() function to load the User.php file from the app folder.

Second, create a new instance of the class App\User and call the avartar() method.

Summary

  • Use the PHP class_exists() function to check if a class exists or not.
  • Use the fully-qualified name for the class if the class is namespaced.

Источник

class_exists

Эта функция проверяет, был ли объявлен указанный класс или нет.

Список параметров

Имя класса. Воспринимается без учёта регистра.

Нужно ли автоматически подгружать класс, если он ещё не загружен.

Возвращаемые значения

Возвращает true , если класс class объявлен, иначе false .

Примеры

Пример #1 Пример использования class_exists()

// Проверяем существование класса перед его использованием
if ( class_exists ( ‘MyClass’ )) $myclass = new MyClass ();
>

Пример #2 Пример использования c параметром autoload

spl_autoload_register (function ( $class_name ) include $class_name . ‘.php’ ;

// Проверяем необходимость подключения указанного класса
if (! class_exists ( $class_name , false )) throw new LogicException ( «Unable to load class: $class_name » );
>
>);

if ( class_exists ( MyClass ::class)) $myclass = new MyClass ();
>

Смотрите также

  • function_exists() — Возвращает true, если указанная функция определена
  • enum_exists() — Проверяет, определено ли перечисление
  • interface_exists() — Проверяет, определён ли интерфейс
  • get_declared_classes() — Возвращает массив с именами объявленных классов

User Contributed Notes 9 notes

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

Note: class_exists() check only classes!
interface DemoInterface <>;
var_dump ( class_exists ( ‘DemoInterface’ )); // false
trait DemoTrait <>;
var_dump ( class_exists ( ‘DemoTrait’ )); // false
class DemoClass <>;
var_dump ( class_exists ( ‘DemoClass’ )); // true
?>

Common function:
/**
* Checks if the class/trait/interface has been defined.
*
* @param string $name The case-insensitive name of class/trait/interface
* @param bool $autoload Whether to call spl_autoload()
* @return bool
*/
function structure_exists ( string $name , bool $autoload = true ): bool
return class_exists ( $name , $autoload )
|| interface_exists ( $name , $autoload )
|| trait_exists ( $name , $autoload );
>
?>

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.

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.

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
class Second <>
?>
file index.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..

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»;

If you have a directory of classes you want to create. (Modules in my instance). you can do it like that

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.

/**
* 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.

/**
* 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!

If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
in_array ( $class_name , get_declared_classes ());
?>

Оцените статью