- Get a list of all available classes with PHP
- Using get_declared_classes()
- Sorting the result into alphabetical order
- Conclusion
- Check Out These Related posts:
- get_declared_classes
- Changelog
- Examples
- See Also
- get_declared_classes
- Changelog
- Examples
- See Also
- get_declared_classes() function in PHP
- Syntax
- Parameters
- Return
- Example
- Output
Get a list of all available classes with PHP
PHP has the function get_declared_classes() which allows you to get a list of all the available system and user defined classes in an array. This post looks at how to use the get_declared_classes() function, the output from it and how to sort the list into alphabetical order.
Using get_declared_classes()
get_declared_classes() returns a zero based array containing all the classes available to your script, including both system declared classes (such as PDO and XMLReader) and the classes you have declared yourself or from any 3rd party libraries you have included in your script.
The following example illustrates this (the examples below assume we have two user defined classed called foo and bar):
print_r(get_declared_classes());
and an extract of the result:
Array ( [0] => stdClass [1] => Exception [2] => ErrorException [3] => LibXMLError [4] => __PHP_Incomplete_Class [5] => php_user_filter . [100] => XMLWriter [101] => XSLTProcessor [102] => foo [103] => bar )
Sorting the result into alphabetical order
If you want to sort the list of classes into alphabetical order, you could do this instead:
$classes = get_declared_classes(); sort($classes); print_r($classes);
and an extract of the result:
Array ( [0] => AppendIterator [1] => ArrayIterator [2] => ArrayObject [3] => BadFunctionCallException [4] => BadMethodCallException [5] => CachingIterator . [100] => mysqli_stmt [101] => mysqli_warning [102] => php_user_filter [103] => stdClass )
Conclusion
The get_declaed_functions() function is a great way of getting a complete list of classes that are available on your install of PHP and from your own and 3rd party PHP libraries.
Check Out These Related posts:
get_declared_classes
Возвращает массив имен объявленных классов в текущем скрипте.
Note:
Обратите внимание, что в зависимости от того, какие расширения вы скомпилировали или загрузили в PHP, могут присутствовать дополнительные классы. Это означает, что вы не сможете определять свои собственные классы, используя эти имена. Список предопределенных классов находится в разделе » Предопределенные классы » в приложениях.
Changelog
Version | Description |
---|---|
7.4.0 | Ранее get_declared_classes () всегда возвращала родительские классы перед дочерними. Это уже не так. Никакой конкретный порядок для возвращаемого значения get_declared_classes () не гарантируется . |
Examples
Пример # 1 get_declared_classes () Пример
print_r(get_declared_classes()); ?>
Из приведенного выше примера будет выведено нечто подобное:
Array ( [0] => stdClass [1] => __PHP_Incomplete_Class [2] => Directory )
See Also
- class_exists () — Проверяет, определен ли класс
- get_declared_interfaces () — возвращает массив всех объявленных интерфейсов
- get_defined_functions () — возвращает массив всех определенных функций
PHP 8.2
(PHP 4,5,7,8)get_current_user Получает имя владельца PHP скрипта Возвращает имя владельца текущего PHP скрипта.
(PHP 8)get_debug_type Получает имя переменной в виде,подходящем для отладки Возвращает разрешенное имя значения переменной PHP.
get_declared_classes
Returns an array of the names of the declared classes in the current script.
Note:
Note that depending on what extensions you have compiled or loaded into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.
Changelog
Version | Description |
---|---|
7.4.0 | Previously get_declared_classes() always returned parent classes before child classes. This is no longer the case. No particular order is guaranteed for the get_declared_classes() return value. |
Examples
Example #1 get_declared_classes() example
The above example will output something similar to:
Array ( [0] => stdClass [1] => __PHP_Incomplete_Class [2] => Directory )
See Also
- class_exists() — Checks if the class has been defined
- get_declared_interfaces() — Returns an array of all declared interfaces
- get_defined_functions() — Returns an array of all defined functions
- Classes/Object Functions
- class_alias
- class_exists
- enum_exists
- get_called_class
- get_class_methods
- get_class_vars
- get_class
- get_declared_classes
- get_declared_interfaces
- get_declared_traits
- get_mangled_object_vars
- get_object_vars
- get_parent_class
- interface_exists
- is_a
- is_subclass_of
- method_exists
- property_exists
- trait_exists
- __autoload
get_declared_classes() function in PHP
The get_declared_classes returns an array with the name of the defined classes.
Syntax
get_declared_classes (void)
Parameters
Return
The get_declared_classes() function returns an array of the names of the declared classes in the current script.
Example
The following is an example −
Output
The following is the output −
Array ( [0] => stdClass [1] => Exception [2] => ErrorException [3] => Error [4] => ParseError [5] => TypeError [6] => ArgumentCountError [7] => ArithmeticError [8] => DivisionByZeroError [9] => Closure [10] => Generator [11] => ClosedGeneratorException [12] => DateTime [13] => DateTimeImmutable [14] => DateTimeZone [15] => DateInterval [16] => DatePeriod [17] => LibXMLError [18] => ReflectionException [19] => Reflection [20] => ReflectionFunctionAbstract [21] => ReflectionFunction [22] => ReflectionGenerator [23] => ReflectionParameter [24] => ReflectionType [25] => ReflectionNamedType [26] => ReflectionMethod [27] => ReflectionClass [28] => ReflectionObject [29] => ReflectionProperty [30] => ReflectionClassConstant [31] => ReflectionExtension [32] => ReflectionZendExtension [33] => LogicException [34] => BadFunctionCallException [35] => BadMethodCallException [36] => DomainException [37] => InvalidArgumentException [38] => LengthException [39] => OutOfRangeException [40] => RuntimeException [41] => OutOfBoundsException [42] => OverflowException [43] => RangeException [44] => UnderflowException [45] => UnexpectedValueException [46] => RecursiveIteratorIterator [47] => IteratorIterator [48] => FilterIterator [49] => RecursiveFilterIterator [50] => CallbackFilterIterator [51] => RecursiveCallbackFilterIterator [52] => ParentIterator [53] => LimitIterator [54] => CachingIterator [55] => RecursiveCachingIterator [56] => NoRewindIterator [57] => AppendIterator [58] => InfiniteIterator [59] => RegexIterator [60] => RecursiveRegexIterator [61] => EmptyIterator [62] => RecursiveTreeIterator [63] => ArrayObject [64] => ArrayIterator [65] => RecursiveArrayIterator [66] => SplFileInfo [67] => DirectoryIterator [68] => FilesystemIterator [69] => RecursiveDirectoryIterator [70] => GlobIterator [71] => SplFileObject [72] => SplTempFileObject [73] => SplDoublyLinkedList [74] => SplQueue [75] => SplStack [76] => SplHeap [77] => SplMinHeap [78] => SplMaxHeap [79] => SplPriorityQueue [80] => SplFixedArray [81] => SplObjectStorage [82] => MultipleIterator [83] => SessionHandler [84] => __PHP_Incomplete_Class [85] => php_user_filter [86] => Directory [87] => AssertionError [88] => CURLFile [89] => finfo [90] => PDOException [91] => PDO [92] => PDOStatement [93] => PDORow [94] => PharException [95] => Phar [96] => PharData [97] => PharFileInfo [98] => SQLite3 [99] => SQLite3Stmt [100] => SQLite3Result [101] => mysqli_sql_exception [102] => mysqli_driver [103] => mysqli [104] => mysqli_warning [105] => mysqli_result [106] => mysqli_stmt )
I love programming (: That’s all I know