Узнать имя текущего класса php
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
)
Функции для работы с классами и объектами
В PHP предусмотрен широкий набор функций для тестирования классов и объектов. Для чего это нужно? Вы, наверняка, сами написали большинство классов, которые используются в сценарии. На самом деле во время выполнения программы не всегда известно, какие классы используются. Например, вы могли разработать систему для «прозрачной» работы со сложными классами, разработанными сторонними производителями. В подобном случае экземпляр объекта обычно создается только на основании имени класса. В PHP разрешается использовать строки, чтобы ссылаться на классы динамически, как показано ниже:
Обычно подобные операции выполняют, когда нужно, чтобы система могла выполнять созданные пользователем подключаемые дополнительные модули (plug-ins). Но прежде чем делать такие рискованные вещи в реальном проекте, вы должны проверить, что указанный класс существует, у него есть нужные вам методы и т.д.
В PHP 5 часть функций для работы с классами была заменена более мощным Reflection API, который мы будем изучать в следующей статье. Однако простота и удобство использования в некоторых случаях делают эти функции более предпочтительными. По этой причине мы сейчас и приступим к их рассмотрению.
Поиск классов
Функции class_exists() передается строка, содержащая имя класса. Она возвращает значение true, если класс существует, и false — в противном случае. С помощью этой функции можно сделать предыдущий фрагмент кода более безопасным:
Конечно, мы не можем быть уверенными, что для конструктора рассматриваемого класса не потребуются аргументы. Для достижения такого уровня безопасности программирования необходимо обратиться к Reflection API, который мы будем изучать в следующей статье. Тем не менее перед его использованием с помощью функции class_exists() мы должны убедиться в том, что нужные нам классы существуют.
Не забывайте, что всегда следует с осторожностью относиться к данным, полученным из внешних источников, и проверять их перед использованием в своем сценарии. В случае получения пути и имени файла следует экранировать или удалять точки и разделители каталогов, тем самым предотвращается возможность взлома сайта, когда недобросовестный пользователь может заменить имена каталогов и включить в них нежелательные файлы.
Чтобы получить массив всех классов, определенных в сценарии, можно воспользоваться функцией get_declared_classes():
В результате будет выведен список встроенных и определенных пользователем классов. Помните, что данная функция возвращает только те классы, которые были объявлены к моменту ее вызова.
Получение информации об объекте или классе
Функция getProduct() просто создает экземпляр объекта CDProduct и возвращает его. Мы воспользуемся данной функцией в этом разделе. Функция get_class() выдает очень специфическую информацию. Обычно же нужна более общая информация о принадлежности к семейству классов. Предположим, нам нужно знать, что объект принадлежит семейству ShopProduct, но при этом не имеет значения, к какому классу конкретно: BookProduct или CDProduct. Для этой цели в PHP предусмотрен оператор instanceof.
Оператор instanceof работает с двумя операндами: объектом, который нужно протестировать (указывается слева от ключевого слова instanceof), и именем класса или интерфейса справа. Оператор возвращает значение true, если объект является экземпляром класса указанного типа:
Получение информации о методах
Чтобы получить список всех методов класса, можно воспользоваться функцией get_class_methods(). В качестве аргумента ей передается имя класса, а она возвращает массив, содержащий имена всех методов класса:
Код PHP 
В этом примере мы передаем имя класса функции get_class_methods() и выводим возвращенный ею массив с помощью цикла foreach. Мы могли бы также передать функции get_class_methods() объект и получили бы такой же результат. Если вы используете не самую старую версию PHP, то в возвращенный список будут включены только имена общедоступных методов.
Получение информации о свойствах
Точно так же, как можно запросить список методов класса, можно запросить и список его полей. Функции get_class_vars() передается имя класса, а она возвращает ассоциативный массив. Имена полей сохраняются в виде ключей этого массива, а значения полей — в виде значений.
Получение информации о наследовании
С помощью функций для работы с классами можно также выявлять отношения наследования. Например, с помощью функции get_parent_class() можно узнать имя родительского класса для указанного класса. Этой функции передается ссылка на объект или имя класса, а она возвращает имя суперкласса, если таковой существует. Если же такого класса нет, т.е. если у проверяемого класса нет родительского класса, то функция вернет значение false. В результате вызова
мы получим имя родительского класса ShopProduct, как и можно было ожидать.
С помощью функции is_subclass_of() можно также проверить, является ли класс дочерним для другого класса. Этой функции передается ссылка на дочерний объект и имя родительского класса. Функция возвращает значение true, если второй класс является суперклассом первого аргумента:
Функция is_subclass_of() сообщит информацию только об отношениях наследования в классе. Но она не поможет вам узнать, реализует ли класс интерфейс. Для этой цели следует использовать оператор instanceof. Кроме того, можно воспользоваться функцией class_implements(), которая является частью SPL (Standard PHP Library — стандартная библиотека PHP). Этой функции передается имя класса или ссылка на объект, а она возвращает массив имен интерфейсов:
Прежде чем отобразить результат, в этом коде мы проверяем, есть ли имя интерфейса в массиве, возвращенном функцией class_implements().
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.
Как получить имя конкретного свойства класса?
Честно искал в гугле минут 20, так и не нашел нужного мне ответа.
Есть св-во класса:
$this->myAmazingPropery = ‘test’;
Но я хочу вместо ручного прописывания сделать метод, аргументом которому передавать массив вида:
Но это только как пример. Лучше конечно, если вы перенесёте интерфейс добавления значений в сессию, в отдельный класс
FanatPHP:
Ну например:
$this->myAmazingPropery = ‘test’;
class_exists
(PHP 4, PHP 5, PHP 7, PHP 8)
class_exists — Проверяет, был ли объявлен класс
Описание
Эта функция проверяет, был ли объявлен указанный класс или нет.
Список параметров
Имя класса. Воспринимается без учёта регистра.
Вызывать ли по умолчанию __autoload.
Возвращаемые значения
Примеры
Пример #1 Пример использования class_exists()
// Проверяем существование класса перед его использованием
if ( class_exists ( ‘MyClass’ )) <
$myclass = new MyClass ();
>
Пример #2 Пример использования c параметром autoload
if ( class_exists ( MyClass ::class)) <
$myclass = new MyClass ();
>
Смотрите также
User Contributed Notes 9 notes
use a\namespaced\classname as coolclass;
class_exists( ‘coolclass’ ) => false
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.
Apparently, the internal list of declared classes is only updated after the autoload function is completed.
Beware: class_exists is case-INsensitive, as is class instantiation.
(tested with PHP 5.5.10 on Linux)
This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:
I’m running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn’t exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.
If you have a directory of classes you want to create. (Modules in my instance). you can do it like that
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.


