PHP - Class/Object get_declared_classes() Function



The PHP Class/Object get_declared_classes() function is used to return an array containing the names of all classes given in the code, whether it is user-defined or built-in. This function is very useful to see what classes are available in your code.

Syntax

Below is the syntax of the PHP Class/Object get_declared_classes() function −

array get_declared_classes (void)

Parameters

This function does not accept any parameters.

Return Value

The get_declared_classes() function returns an array of the names of the declared classes in the current script.

PHP Version

First introduced in core PHP 4, the get_declared_classes() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here is the basic example of the PHP Class/Object get_declared_classes() function to get an array of the names of the declared classes.

<?php
   print_r(get_declared_classes());
?>

Output

Here is the outcome of the following code −

Array
(
   [0] => InternalIterator
   [1] => Exception
   .
   .
   .
   [245] => Ds\Set
   [246] => Ds\PriorityQueue
   [247] => Ds\Pair
)

Example 2

In the below PHP code we will use the get_declared_classes() function and list all declared classes after defining a few classes.

<?php
   // Declare the classes
   class MyClass1 {}
   class MyClass2 {}
   
   $classes = get_declared_classes();
   print_r($classes);
?> 

Output

This will generate the below output −

Array
(
  [0] => InternalIterator
  [1] => Exception
  .
  .
  .
  [248] => MyClass1
  [249] => MyClass2
)

Example 3

Now the below code demonstrates how to check if a specific class is declared in the script using the get_declared_classes() function.

<?php
   // Declare MyClass here
   class MyClass {}

   $classes = get_declared_classes();
   if (in_array('MyClass', $classes)) {
       echo "MyClass is declared.";
   } else {
       echo "MyClass is not declared.";
   }
?> 

Output

This will create the below output −

MyClass is declared.

Example 4

This example shows how get_declared_classes() function works after including another file that defines additional classes.

<?php
   include '/PHP/PhpProjects/other_file.php';

   $classes = get_declared_classes();
   print_r($classes);
?> 

Here is the code written in the other_file.php file −

<?php
   class OtherClass {}
?> 

Output

Following is the output of the above code −

Array
(
  [0] => InternalIterator
  [1] => Exception
  .
  .
  .
  [248] => OtherClass
)
php_function_reference.htm
Advertisements