php get declared classes

get_declared_classes

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

Возвращает объявленные классы.

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

У этой функции нет параметров.

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

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

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

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

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

Примеры

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

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

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

User Contributed Notes 9 notes

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

//. and four
class classfour

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

Regarding note of 3-21:

?>

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.

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.

Its not a Bug it a.

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.

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.

This function considers only classes and subclasses. Not subsubclasses.

Источник

get_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class — Returns the name of the class of an object

Description

Parameters

The tested object. This parameter may be omitted when inside a class.

Note: Explicitly passing null as the object is no longer allowed as of PHP 7.2.0. The parameter is still optional and calling get_class() without a parameter from inside a class will work, but passing null now emits an E_WARNING notice.

Return Values

Returns the name of the class of which object is an instance. Returns false if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

If the object is an instance of a class which exists in a namespace, the qualified namespaced name of that class is returned.

Errors/Exceptions

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

Changelog

Examples

Example #1 Using get_class()

// create an object
$bar = new foo ();

The above example will output:

Example #2 Using get_class() in superclass

class foo extends bar <
>

The above example will output:

Example #3 Using get_class() with namespaced classes

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

The above example will output:

See Also

User Contributed Notes 36 notes

::class
fully qualified class name, instead of get_class

namespace my \ library \ mvc ;

print Dispatcher ::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher ;

(For reference, here’s the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

class Foo
<
public function __construct ()
<
echo «Foo» ;
>
>

People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here’s a good example that should fix that for ever:

class Bar extends Foo <

$foo = new Foo ();
$bar = new Bar ();
$quux = new Quux ();

—doMethod—
Foo::doMethod
Foo::doMethod
Quux::doMethod

—doGetClassThis—
Foo::doThat
Bar::doThat
Quux::doThat

—doGetClass—
Foo::doThat
Foo::doThat
Quux::doThat

In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not ‘know’ the name of the calling subclass’, so I use a backtrace to determine it. I don’t like hacks like this, but as long as PHP doesn’t have an alternative, this is what has to be done:

Simplest way how to gets Class without namespace

namespace a \ b \ c \ d \ e \ f ;

echo new Foo (); // prints Foo
?>

Need a quick way to parse the name of a class when it’s namespaced? Try this:

/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) <
$classname = get_class($obj);

With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

namespace Foo \ Bar ;

class Snafu extends Baz
<
>

__CLASS__ Foo\Bar\Baz Baz
get_called_class Foo\Bar\Snafu Snafu

The code in my previous comment was not completely correct. I think this one is.

/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() <
$implementing_class = static::$__CLASS__;
$original_class = __CLASS__;

There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

private function __construct () <
// Singleton
>
>

class MySubclass extends MySuperclass <
>

Although you can call a class’s static methods from an instance of the class as though they were object instance methods, it’s nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

If you want the path to an file if you have i file structure like this

and foo() in foo.php extends controller() in controller.php like this

namespace system \ modules \ foo ;

class foo extends \ system \ libs \ controller <
public function __construct () <
parent :: __construct ();
>
>
?>

and you want to know the path to foo.php in controller() this may help you

namespace system \ libs ;

well, if you call get_class() on an aliased class, you will get the original class name

Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it’s not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

default: throw new Exception ( «Unknown backtrace method type» );
>
>
>

class B extends Singleton <
>

class C extends Singleton <
>

Method for pulling the name of a class with namespaces pre-stripped.

namespace testme \ here ;

public function test ()
<
return get_class_name ( get_class ());
>
>

As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the «self» keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the «self» keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

However, assuming compile-time binding (where the keyword «self» refers to the class in which the method is defined), which is how php works, the output would be:

The oddity here is that «$this» is bound at runtime to the actual class of the object (obviously) but «self» is bound at compile-time, which seems counter-intuitive to me. «self» is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which «self» ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to «self» being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the «self» keyword for static methods:

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

I realise that some people might respond «why don’t use just just the class name with ‘ Class’ appended instead of the classDisplayName() method», which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.

Источник

How to get all class names inside a particular namespace?

I want to get all classes inside a namespace. I have something like this:

I tried get_declared_classes() inside getAllClasses() but MyClass1 and MyClass2 were not in the list.

How could I do that?

php get declared classes. Смотреть фото php get declared classes. Смотреть картинку php get declared classes. Картинка про php get declared classes. Фото php get declared classes

15 Answers 15

The generic approach would be to get all fully qualified classnames (class with full namespace) in your project, and then filter by the wanted namespace.

PHP offers some native functions to get those classes (get_declared_classes, etc), but they won’t be able to find classes that have not been loaded (include / require), therefore it won’t work as expected with autoloaders (like Composer for example). This is a major issue as the usage of autoloaders is very common.

So your last resort is to find all PHP files by yourself and parse them to extract their namespace and class:

If you follow PSR 0 or PSR 4 standards (your directory tree reflects your namespace), you don’t have to filter anything: just give the path that corresponds to the namespace you want.

php get declared classes. Смотреть фото php get declared classes. Смотреть картинку php get declared classes. Картинка про php get declared classes. Фото php get declared classes

That package can be found here: haydenpierce/class-finder.

See more info in the README file.

I wasn’t happy with any of the solutions here so I ended up building my class to handle this. This solution requires that you are:

The contiguous sub-namespace names after the «namespace prefix» correspond to a subdirectory within a «base directory», in which the namespace separators represent directory separators. The subdirectory name MUST match the case of the sub-namespace names.

Pretty interesting that there does not seem to be any reflection method that does that for you. However I came up with a little class that is capable of reading namespace information.

In order to do so, you have to traverse trough all defined classes. Then we get the namespace of that class and store it into an array along with the classname itself.

The output will be:

array(2) < [0]=>string(17) «ClassTwo\ClassTwo» [1]=> string(20) «ClassTwo\ClassTwoNew» >

Of course everything besides the NameSpaceFinder class itself if assembled quick and dirty. So feel free to clean up the include mess by using autoloading.

Quite a few interesting answers above, some actually peculiarly complex for the proposed task.

To add a different flavor to the possibilities, here a quick and easy non-optimized function to do what you ask using the most basic techniques and common statements I could think of:

I’ve written this function to assume you are not adding the last «trailing slash» ( \ ) on the namespace, so you won’t have to double it to escape it. 😉

Please notice this function is only an example and has many flaws. Based on the example above, if you use ‘ namespace\sub ‘ and ‘ namespace\sub\deep ‘ exists, the function will return all classes found in both namespaces (behaving as if it was recursive). However, it would be simple to adjust and expand this function for much more than that, mostly requiring a couple of tweaks in the foreach block.

It may not be the pinnacle of the code-art-nouveau, but at least it does what was proposed and should be simple enough to be self-explanatory.

I hope it helps pave the way for you to achieve what you are looking for.

Источник

get_class

get_class — Возвращает имя класса, к которому принадлежит объект

Описание

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

Тестируемый объект. Внутри класса этот параметр может быть опущен.

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

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Если параметр object является экземпляром класса, существующего в пространстве имен, то будет возвращено полное имя с указанием пространства имен.

Ошибки

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

ВерсияОписание
7.2.0До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удален как значение по умолчанию для object и больше не является допустимым значением.

Примеры

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

// создание объекта
$bar = new foo ();

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

Пример #2 Использование get_class() в родительском классе

class foo extends bar <
>

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

Пример #3 Использование get_class() с классами в пространствах имен

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

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

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

Источник

get_declared_classes

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

Описание

Возвращает объявленные классы.

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

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

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

Примеры

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

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

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

Коментарии

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

//. and four
class classfour

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

Regarding note of 3-21:

?>

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.

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.

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.

This function considers only classes and subclasses. Not subsubclasses.

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

?>

will output the same result.

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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *