узнать имя текущего класса php

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 — Возвращает имя класса, к которому принадлежит объект

Описание

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

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

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

Если параметр 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 ;

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

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

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.

Источник

Использование ключевого слова ::class в PHP

узнать имя текущего класса php. Смотреть фото узнать имя текущего класса php. Смотреть картинку узнать имя текущего класса php. Картинка про узнать имя текущего класса php. Фото узнать имя текущего класса php

Если вы уже достаточно продолжительное время работаете с PHP и современными PHP фреймворками, то скорее всего вы уж не раз встречались с ключевым словом ::class. В данной статье мы поговорим, о том, что означает это ключевое слово и где его можно использовать.

При работе с пространствами имен в PHP, часто приходится писать полные имена классов. Особенно это проявляется при работе с современными MVC фреймворками, которые вовсю используют новомодные фишки PHP. Давайте посмотрим на реальный пример.

Ключевое слово класс ::class

Начиная с PHP версии 5.5 ключевое слово ::class используется для разрешения имени класса. Это означает, что оно возвращает полное имя класса, что особенно полезно, при работе с длинными именами классов. Посмотрим на пример:

Реальные примеры применения

Как работает ключевое слово ::class мы увидели. Но где оно может быть применено? Есть несколько случаев, где это ключевое слово может быть полезно. Если вы поищете этого ключевое слово во фреймворке Laravel, вы получите сотни результатов.

Давайте посмотрим, как это ключевое слово может быть применено:

Здесь нам необходимо передать имя класса в метод belongsTo. Здесь-то мы и можем использовать ключевое слово ::class.

Таким образом, мы получаем два преимущества. Во-первых, нужно меньше писать. Во-вторых, поскольку мы не пишем имя класса, как строку, наша среда разработки предоставляет нам мощное средство – автодополнение кода.

Заключение

Когда это уместно, используйте ключевое слово class. Во-первых, ваша работа ускорится и повысится ее качество. Во-вторых, если вы видите что-то, что вы, не совсем понимаете, попробуйте это выяснить. Потратьте некоторое время и покопайтесь в своем фреймворке, проекте или просто языке программирования.

узнать имя текущего класса php. Смотреть фото узнать имя текущего класса php. Смотреть картинку узнать имя текущего класса php. Картинка про узнать имя текущего класса php. Фото узнать имя текущего класса php

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Комментарии ( 0 ):

Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.

Источник

Узнать имя текущего класса php

Класс может содержать собственные константы, переменные (называемые свойствами) и функции (называемые методами).

Пример #1 Простое определение класса

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

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

Если с директивой new используется строка ( string ), содержащая имя класса, то будет создан новый экземпляр этого класса. Если имя находится в пространстве имён, то оно должно быть задано полностью.

В случае отсутствия аргументов в конструктор класса, круглые скобки после названия класса можно опустить.

Пример #3 Создание экземпляра класса

Когда происходит присвоение уже существующего экземпляра класса новой переменной, то эта переменная будет указывать на этот же экземпляр класса. То же самое происходит и при передаче экземпляра класса в функцию. Копию уже созданного объекта можно создать через её клонирование.

Пример #4 Присваивание объекта

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

Создавать экземпляры объекта можно двумя способами:

Пример #5 Создание новых объектов

class Test
<
static public function getNew ()
<
return new static;
>
>

class Child extends Test
<>

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

Обратиться к свойству или методу только что созданного объекта можно с помощью одного выражения:

Пример #6 Доступ к свойствам/методам только что созданного объекта

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

Замечание: До PHP 7.1 аргументы не имели значения, если не определена функция конструктора.

Свойства и методы

Пример #7 Доступ к свойству vs. вызов метода

public function bar () <
return ‘метод’ ;
>
>

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

Это означает, что вызвать анонимную функцию, присвоенную переменной, напрямую не получится. Вместо этого свойство должно быть назначено, например, переменной. Можно вызвать такое свойство напрямую, заключив его в скобки.

Пример #8 Вызов анонимной функции, содержащейся в свойстве

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

extends

Класс может наследовать константы, методы и свойства другого класса используя ключевое слово extends в его объявлении. Невозможно наследовать несколько классов, один класс может наследовать только один базовый класс.

Наследуемые константы, методы и свойства могут быть переопределены (за исключением случаев, когда метод класса объявлен как final) путём объявления их с теми же именами, как и в родительском классе. Существует возможность доступа к переопределённым методам или статическим свойствам путём обращения к ним через parent::

Пример #9 Простое наследование классов

class ExtendClass extends SimpleClass
<
// Переопределение метода родителя
function displayVar ()
<
echo «Расширенный класс\n» ;
parent :: displayVar ();
>
>

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

Правила совместимости сигнатуры

Пример #10 Совместимость дочерних методов

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

Следующие примеры демонстрируют, что дочерний метод, который удаляет параметр или делает необязательный параметр обязательным, несовместим с родительским методом.

Пример #11 Фатальная ошибка, когда дочерний метод удаляет параметр

class Extend extends Base
<
function foo ()
<
parent :: foo ( 1 );
>
>

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

Пример #12 Фатальная ошибка, когда дочерний метод делает необязательный параметр обязательным.

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

Переименование параметра метода в дочернем классе не является несовместимостью сигнатуры. Однако это не рекомендуется, так как приведёт к Error во время выполнения, если используются именованные аргументы.

Пример #13 Ошибка при использовании именованных аргументов и параметров, переименованных в дочернем классе

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

::class

Пример #14 Разрешение имени класса

namespace NS <
class ClassName <
>

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

Разрешение имён класса с использованием ::class происходит на этапе компиляции. Это означает, что на момент создания строки с именем класса автозагрузки класса не происходит. Как следствие, имена классов раскрываются, даже если класс не существует. Ошибка в этом случае не выдаётся.

Пример #15 Отсутствует разрешение имени класса

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

Начиная с PHP 8.0.0, константа ::class также может использоваться для объектов. Это разрешение происходит во время выполнения, а не во время компиляции. То же самое, что и при вызове get_class() для объекта.

Пример #16 Разрешение имени объекта

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

Методы и свойства Nullsafe

Пример #17 Оператор Nullsafe

Оператор nullsafe лучше всего использовать, когда null считается допустимым и ожидаемым значением для возвращаемого свойства или метода. Для индикации ошибки предпочтительнее выбрасывать исключение.

User Contributed Notes 11 notes

I was confused at first about object assignment, because it’s not quite the same as normal assignment or assignment by reference. But I think I’ve figured out what’s going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object’s «handle» goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

Источник

get_class_vars

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

get_class_vars — Возвращает объявленные по умолчанию свойства класса

Описание

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

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

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

Примеры

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

$my_class = new myclass ();

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

Пример #2 get_class_vars() и поведение области видимости

public static function expose ()
<
echo format ( get_class_vars ( __CLASS__ ));
>
>

TestCase :: expose ();
echo format ( get_class_vars ( ‘TestCase’ ));
?>

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

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

User Contributed Notes 15 notes

public static function getFields ()
<
return self :: _getFields ( __CLASS__ );
>

abstract public static function getFields ();

var_dump ( childClass :: getFields ());
?>

Results:
array(4) <
[0]=>
string(2) «id»
[1]=>
string(4) «name»
[2]=>
string(10) «idInParent»
[3]=>
string(12) «nameInParent»
>

All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array. For serialization I recommend:

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.

I needed to get only the class static variables, leaving out instance variables.

If you need get the child protected/private vars ignoring the parent vars, use like this:

$child_class = new childClass ();
?>

If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

class Foo <
const Bar = «error» ;

print_r ( get_class_vars ( «Foo» ));

?>

. but using «Foo::Bar» instead «self::Bar» will work 😉

class someClass <
public function toArray () <
$records = array();

in PHP5 to get all the vars (including private etc.) use:

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.

Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

( get_class_vars ( «Foo» ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).

This is one of the best php functions. Look at what you can do

Now you can do really cool things. If you have a form like

when you submmit the form, you can get the data like

$person = new Person($_POST);

This is my core Object for everthing I do and it works great.

get_class_vars_assoc()
— Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

public static function load () <
print_r ( self :: get_class_vars_assoc ());
>

[ParentClass] => Array
(
[1] => parentVar
[2] => in_parent_and_child
)

[GrandClass] => Array
(
[0] => grandVar
[1] => in_grand_and_parent
[2] => in_grand_and_child
)

Источник

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

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