Вывести имя класса php

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

(PHP 4, PHP 5, PHP 7)

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

Описание

Возвращает имя класса, экземпляром которого является объект object .

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

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

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

Возвращает имя класса, к которому принадлежит экземпляр object . Возвращает FALSE , если object не является объектом.

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

Ошибки

Если get_class() будет вызвана с чем-то другим, не являющимся объектом, будет вызвана ошибка уровня E_WARNING .

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

Версия Описание
5.3.0 NULL стал значением по умолчанию для параметра object , поэтому передача NULL в object теперь имеет тот же самый эффект, как и отсутствие какой-либо передачи вообще.

Примеры

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

class foo <
function name ()
<
echo «My name is » , get_class ( $this ) , «\n» ;
>
>

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

// внешний вызов
echo «Its name is » , get_class ( $bar ) , «\n» ;

// внутренний вызов
$bar -> name ();

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

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

abstract class bar <
public function __construct ()
<
var_dump ( get_class ( $this ));
var_dump ( get_class ());
>
>

class foo extends bar <
>

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

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

  • get_called_class() — Имя класса, полученное с помощью позднего статического связывания
  • get_parent_class() — Возвращает имя родительского класса для объекта или класса
  • gettype() — Возвращает тип переменной
  • is_subclass_of() — Проверяет, содержит ли объект в своем дереве предков указанный класс

Источник

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()

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

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

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

User Contributed Notes 9 notes

Regarding note of 3-21:

$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

//. and four
class classfour

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

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.

Take extra care when checking for existence of a class. Following example is, potentially, error prone: ( $className , $classget_declared_classes () ) ?>

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

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

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.

Источник

Как в PHP получить имя класса без неймспейса

Если вы любите баловаться с наследованием классов, то рано или поздно сталкиваетесь с задачей когда нужно узнать имя класса в контексте которого выполняется тот или иной код. Однако, стандартные методы по типу использования магической константы __CLASS__ или get_class($this) возвращают имя класса с его полным неймспейсом. Т.е. вы хотите получить LockHandler, но получаете Component\Filesystem\LockHandler.

Естественно, неокрепшему уму придёт сразу мысль: разбить строку на фрагменты разделённые символом «\» и взять последний фрагмент. Однако, это не самое лучшее решение. Существует ещё одно более простое, быстрое и нативное решение: использование рефлексии!

PHP фреймворк Laravel предлагает ещё один вариант:

Также на просторах интернета встречаются и другие варианты:

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

Читайте также

На чистом PHP данная задача не реализуема, но есть небольшой лайфхак: $nanotime = system(‘date +%s%N’); В результате $nanotime будет содержать…

Стандартные библиотеки PHP умеют генерировать только целые случайные числа. Однако, возникают задачи где нужно не целое рандомное число с максимально…

Казалось бы http_build_query — простая функция, однако, имеет некоторые особенности. Нельзя однозначно сказать что это баг, скорее просто недокументированная фича,…

Источник

Как получить имя класса в PHP?

в Java, мы можем получить имя класса с String className = MyClass.class.getSimpleName();

как это сделать в PHP? Я уже знаю get_class() , но это работает только для объектов. В настоящее время я работаю в Active Record. Мне нужно заявление, как MyClass::className .

7 ответов

начиная с PHP 5.5 вы можете использовать разрешение имен классов через ClassName:: class.

Если вы хотите использовать эту функцию в метод класса static:: class:

для более старых версий PHP, вы можете использовать get_class ().

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

похоже, вы сами ответили на свой вопрос. get_class даст вам имя класса. Это процедурно, и, возможно, именно это вызывает путаницу. Взгляните на документацию php для get_class

чтобы сделать его более похожим на ваш пример, вы можете сделать что-то вроде:

теперь вы можете сделать:

это несколько ограничено, однако, потому что если мой класс расширен он все равно вернет «MyClass». Мы можем использовать get_called_class вместо этого, который полагается на Поздняя Статическая Привязка, относительно новая функция и требует PHP >= 5.3.

теперь у меня есть ответ на мою проблему. Спасибо бред для ссылки я нахожу ответ здесь. И спасибо Я. Деньги за идею. Мое решение:

Я думаю, что важно упомянуть небольшую разницу между «собой» и «статическим» в PHP, поскольку «лучший ответ» использует «статический», который может дать запутанный результат некоторым людям.

чтобы получить имя класса, вы можете использовать ReflectionClass

Источник

get_class_vars

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

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

Описание

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

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

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

Возвращает ассоциативный массив объявленных свойств класса, видимых из текущей области видимости, с их значением по умолчанию. Получившиеся элементы массива имеют форму varname => value . В случае возникновения ошибки возвращается false .

Примеры

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

var $var1 ; // переменная не имеет начального значения.
var $var2 = «xyz» ;
var $var3 = 100 ;
private $var4 ;

// конструктор
function __construct () <
// изменим значения некоторых свойств
$this -> var1 = «foo» ;
$this -> var2 = «bar» ;
return true ;
>

$my_class = new myclass ();

$class_vars = get_class_vars ( get_class ( $my_class ));

foreach ( $class_vars as $name => $value ) <
echo » $name : $value \n» ;
>

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

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

function format ( $array )
<
return implode ( ‘|’ , array_keys ( $array )) . «\r\n» ;
>

class TestCase
<
public $a = 1 ;
protected $b = 2 ;
private $c = 3 ;

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

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

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

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

  • get_class_methods() — Возвращает массив имён методов класса
  • get_object_vars() — Возвращает свойства указанного объекта

User Contributed Notes 15 notes

If you want to retrieve the class vars from within the class itself, use $this.

var $a ;
var $b ;
var $c ;
var $d ;
var $e ;

function GetClassVars ()
<
return array_keys ( get_class_vars ( get_class ( $this ))); // $this
>

$class_vars = $Foo -> GetClassVars ();

foreach ( $class_vars as $cvar )
<
echo $cvar . «
\n» ;
>
?>

Produces, after PHP 4.2.0, the following:

So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 ( class childClass extends parentClass
<
public $id ;
public $name ;

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

>
abstract class parentClass
<
public $idInParent ;
public $nameInParent ;

abstract public static function getFields ();

final protected static function _getFields ( $className )
<
$rtn = array();
foreach ( array_keys ( get_class_vars ( $className )) as $var ) <
$rtn [] = $var ;
>
return $rtn ;
>

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:

= get_class ( $this );
$varTemplate = get_class_vars ( $cName )
foreach ( $varTemplate as $name => $defaultVal ) <
$vars [ $name ] = $this -> $name ; // gets actual val.
>
?>

No scan the $vars and create serialization string how you wish.

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.

function get_static_vars ( $class ) <
$result = array();
foreach ( get_class_vars ( $class ) as $name => $default )
if (isset( $class ::$ $name ))
$result [ $name ] = $default ;
return $result ;
>
?>

That function returns only the public ones. The same pattern can be used inside a class, then it returns private and protected static variables, too:

static protected function get_static_vars ( $class = NULL ) <
if (!isset( $class )) $class = get_called_class ();
$result = array();
foreach ( get_class_vars ( $class ) as $name => $default )
if (isset( $class ::$ $name ))
$result [ $name ] = $default ;
return $result ;
>
?>

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

class childClass extends parentClass <
private $login ;
private $password ;

public function __set ( $key , $val ) <
if ( $key == ‘password’ )
$this -> $key = md5 ( $val );
else
$this -> $key = $val ;
>
>
class parentClass <
public $name ;
public $email ;

function __construct () <
$reflection = new ReflectionClass ( $this );
$vars = array_keys ( $reflection -> getdefaultProperties ());
$reflection = new ReflectionClass ( __CLASS__ );
$parent_vars = array_keys ( $reflection -> getdefaultProperties ());

$my_child_vars = array();
foreach ( $vars as $key ) <
if (! in_array ( $key , $parent_vars )) <
$my_child_vars [] = $key ;
>
>

$child_class = new childClass ();
?>

There seems to be be a function to get constants missing , i.e. get_class_constants() . so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

function GetClassConstants ( $sClassName ) <
$oClass = new ReflectionClass ( $sClassName );
return $oClass -> getConstants ());
>
?>

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» ;

public $Foo = self :: Bar ;
>

print_r ( get_class_vars ( «Foo» ));

?>

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

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

foreach( $this as $key => $value ) <
$records [ $key ] = $value ;
>

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

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();

I propse following for getting Public members, always:
if (! function_exists ( «get_public_class_vars» )) <
function get_public_class_vars ( $class ) <
return get_class_vars ( $class );
>
>
if (! function_exists ( «get_public_object_vars» )) <
function get_public_object_vars ( $object ) <
return get_object_vars ( $object );
>
>
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

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.

class Foo <
public $x ;
protected $y ;
private $z ;
public function __sleep () <
return( get_class_vars ( __CLASS__ ) );
>
>
?>

works fine (returns x, y, & z). However, given the same class as above,

( 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

class Object
<
var $updtFields;//keep track of affected values
function Object($record=»») <
if (is_array($record))
<
$this->updtFields = array();
foreach(array_keys(get_class_vars(get_class($this))) as $k)
if (isset($record[$k]))
<
$this->$k = $record[$k];
$this->updtFields[] = $k;
>
>
>//end of arrayToObject

function toDebug($nl=’
‘)
<
foreach(array_keys(get_class_vars(get_class($this))) as $k)
echo «$k = [» . $this->$k . «]<$nl>«;
>//end of toDebug
>

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

and you define your class like this
class Person extends Object <
var $name; //same same as in the form
var $phone;
>

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

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

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.

class GrandClass <
public $grandVar ;
public $in_grand_and_parent ;
public $in_grand_and_child ;

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

protected static function get_class_vars_assoc () <
$called = get_called_class ();
//echo «called: $called \n»;
$classVars [ $called ] = array_keys ( get_class_vars ( $called ));

$parent = get_parent_class ( $called );
while ( $parent !== FALSE ) <
//echo «parent: $parent \n»;
$classVars [ $parent ] = array_keys ( get_class_vars ( $parent ));
$classVars [ $called ] = array_diff ( $classVars [ $called ],
$classVars [ $parent ]);
if ( isset( $prevParentVars ) ) <
$prevParentVars = array_diff ( $prevParentVars ,
$classVars [ $parent ]);
>

$prevParentVars = & $classVars [ $parent ];
$parent = get_parent_class ( $parent );
>

class ParentClass extends GrandClass <
public $in_grand_and_parent ;
public $parentVar ;
public $in_parent_and_child ;
>

class ChildClass extends ParentClass <
public $in_grand_and_child ;
public $in_parent_and_child ;
public $childVar ;
>

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

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

Источник

Читайте также:  Можно ли отмыть битум с машины сольвентом
Оцените статью