Get classes list php

get_declared_classes

Возвращает массив имён объявленных классов в текущем скрипте.

Замечание:

Учтите также, что в зависимости от модулей, собранных или загруженных в PHP, может варьироваться число дополнительных классов. Это означает, что вы не сможете использовать собственные классы с данными именами. Список предопределённых классов находится в разделе дополнения «Предопределённые классы».

Список изменений

Версия Описание
7.4.0 Ранее get_declared_classes() всегда возвращала родительские классы перед дочерними классами. Это больше не так. Для возвращаемого значения get_declared_classes() конкретный порядок не гарантируется.

Примеры

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

Результатом выполнения данного примера будет что-то подобное:

Array ( [0] => stdClass [1] => __PHP_Incomplete_Class [2] => Directory )

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

  • class_exists() — Проверяет, был ли объявлен класс
  • get_declared_interfaces() — Возвращает массив всех объявленных интерфейсов
  • get_defined_functions() — Возвращает массив всех определённых функций

User Contributed Notes 9 notes

$class = ‘myclass’ ;
$instance = new $class ();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It’s hardly a pointless function.

The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

//define classone
class classone

//define classtwo
class classtwo

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

//define classthree
class classthree

//Shows the same result as before with class three and four appended
print_r ( get_declared_classes ());

Array
(
[0] => stdClass
[1] . other defined classes.
[10] => classone
[11] => classtwo
)

Array
(
[0] => stdClass
[1] . other defined classes.
[10] => classone
[11] => classtwo
[12] => classthree
[13] => classfour
)

get-declared-classes makes no sense at all, if u maybe, later for production, merge class files in one package file.

lets say: package.php
print_r(get_declared_classes());
class declaredHere < >
print_r(get_declared_classes());

so in this case, the declaredHerr class is defined at the first call of print_r();
because PHP-complier runs a hole file and declare Stuff before running the code.

But (Lovely PHP):
print_r(get_declared_classes());
if(true)class declaredHere < >
>
print_r(get_declared_classes());
Will print the declaredHere class only in the second print_r.

Summary:
* in PHP 5.1 class names have case preserved
* contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when checking for existence of a class. Following example is, potentially, error prone:

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

$exists = FALSE ;
$className = strtolower ( $className );
foreach ( get_declared_classes () as $c ) if ( $className === strtolower ( $c ) ) $exists = TRUE ;
break;
>
> ?>

Optimization of the above snippet is left as a simple excercise to the reader 😉
— dexen deVries

classes can’t be unloaded. probably not very practical to implement that in a future version. I wouldn’t go out of my way to do it if I were zend. you’re better off finding a workaround. it’s better programming technique to find a way around having to do that anyway.

you cannot remove them. they are «defined», which happens when the class is being loaded from the parser. you just deleted an instance of a class.

This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes — which is why my subclasses are not listed within the returned array.

In PHP5, you don’t get declared interfaces by calling this function.
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.

those above comments are too old.
now, whatever the order is, the output will be the same:

?>

will output the same result.

  • Функции работы с классами и объектами
    • 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

    Возвращает массив имен объявленных классов в текущем скрипте.

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

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    Allows you to list full qualified class names in directories and files.

    License

    WyriHaximus/php-list-classes-in-directory

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    List all PHP classes in directories and files

    Latest Stable Version Total Downloads Code Coverage License

    To install via Composer, use the command below, it will automatically detect the latest version and bind it with ^ .

    composer require wyrihaximus/list-classes-in-directory 

    get a list of classes from multiple directories.

    use function WyriHaximus\listClassesInDirectories; use function WyriHaximus\listInstantiatableClassesInDirectories; use function WyriHaximus\listNonInstantiatableClassesInDirectories; // $classes now contains a list of full qualified class names from 'src/' and 'tests/' $classes = listClassesInDirectories( __DIR__ . '/src', __DIR__ . '/tests' ); // use listInstantiatableClassesInDirectories() or listNonInstantiatableClassesInDirectories() to only consider classes that can actually be instantiated, or not. $instantiatableClasses = listInstantiatableClassesInDirectory( __DIR__ . '/src', __DIR__ . '/tests' ); $nonInstantiatableClasses = listNonInstantiatableClassesInDirectory( __DIR__ . '/src', __DIR__ . '/tests' );

    get a list of classes from one directory.

    use function WyriHaximus\listClassesInDirectory; use function WyriHaximus\listInstantiatableClassesInDirectory; use function WyriHaximus\listNonInstantiatableClassesInDirectory; // $classes now contains a list of full qualified class names from __DIR__ $classes = listClassesInDirectory(__DIR__); // use listInstantiatableClassesInDirectory() or listNonInstantiatableClassesInDirectory() to only consider classes that can actually be instantiated, or not. $instantiatableClasses = listInstantiatableClassesInDirectory(__DIR__); $nonInstantiatableClasses = listNonInstantiatableClassesInDirectory(__DIR__);

    get a list of classes from multiple files.

    use function WyriHaximus\listClassesInFiles; // $classes now contains a list of full qualified class names from 'Bar.php' and 'Foo.php' $classes = listClassesInFiles( __DIR__ . '/Bar.php', __DIR__ . '/Foo.php' );

    get a list of classes from one file.

    use function WyriHaximus\listClassesInFile; // $classes now contains a list of full qualified class names from 'Foo.php' $classes = listClassesInFile(__DIR__.'/Foo.php');

    This package is a shorthand function for using better reflection and is based on one of the examples .

    Copyright (c) 2018 Cees-Jan Kiewiet

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    About

    Allows you to list full qualified class names in directories and files.

    Источник

    Читайте также:  Font names in python
Оцените статью