PHP: get_class - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

get_declared_classes get_class_vars

Last updated: Sat, 27 Jan 2007

view this page in

# get_class

(PHP 4, PHP 5)

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

## Description

string get_class ( object obj )

Функция возвращает имя класса экземпляром которого является объект `obj`. Если `obj` не является объектом, функция вернет `FALSE`

> Замечание: Внутренние классы PHP, объявленные в расширениях возвращаются в оригинальном регистре. В PHP 4, функция get_class() возвращает имя класса в нижнем регистре, однако в PHP 5 имя также возвращается в оригинальном регистре, аналогично классам расширений.

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

`<?php
class foo {
function foo()
{
// имплементация чего-либо
}
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}
// создание объекта
$bar = new foo();
// внешний вызов
echo "Its name is " , get_class($bar) , "\n";
// внутренний вызов
$bar->name();
?>`

выведет:

    Its name is foo
    My name is foo

См. также get_parent_class(), gettype() и is_subclass_of().

add a note User Contributed Notes
get_class
spam at matsgefvert dot se
24-Feb-2007 01:37
`I disagree with the notion that the authors of the previous posts are unfamiliar with OOP. Without the ability to know from general (parent) objects what kind of classes we're operating on, it makes things rather difficult, especially in building frameworks that rely heavily on class types (e.g. persistence layers).
The proposed BooBoof::getclass() and CooCoof::getclass() scheme will not work in some particular scenarios since static calls aren't virtual, which means a parent class will always call its own getclass() function instead of the one needed to find out the class name.
The only solution I've found is to pass along a string containing the class name we're working on to the generalized functions. It is however an ugly solution, certainly less than ideal and goes against what OOP and reflection is all about, IMHO.`
yicheng zero-four at gmail dot com
18-Jan-2007 12:22
`This a response to luke at liveoakinteractive dot com and davidc at php dot net. Static methods and variables, by definition, are bound to class types not object instances. You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious. Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).
Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it. The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class. The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass(). So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?" The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior. CooCoof::getclass() will have the expected behavior.`
makc dot the dot great at gmail dot com
17-Dec-2006 09:29
`Check it out:
<?php
class A {
function s () { return "A::s"; }
function s1 () { return $this->s(); }
}
class B extends A {
function s () { return "B::s"; }
}
$a = new A(); echo $a->s1();
echo "<br>";
$b = new B(); echo $b->s1();
echo "<br>";
class C {
static function s () { return "C::s"; }
static function s1 () { return self::s(); }
}
class D extends C {
static function s () { return "D::s"; }
}
echo C::s1();
echo "<br>";
echo D::s1();
echo "<br>";
?>
Output:
A::s
B::s
C::s
C::s
Seems like static function always belong to its class.`
luke at liveoakinteractive dot com
06-Dec-2006 07:03
`This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.
Observe the following:
<?php
class BooBoof {
public static function getclass() {
return __CLASS__;
}
public function retrieve_class() {
return get_class($this);
}
}
class CooCoof extends BooBoof {
}
echo CooCoof::getclass();
// outputs BooBoof
$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>
__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.`
benjaminhill at gmail dot com
27-Apr-2006 10:47
`More funkyness:
class Parent {
function displayTableName() {
echo get_class($this);
echo get_class();
}
}
class Child {
function __construct() {
$this->displayTableName();
}
}
Will return
- Child
- Parent
So when they say "the object isn't required in PHP5" - they don't really mean it.`
brjann at NOSPAMATALLgmail dot com
16-Nov-2005 12:39
`This behavior is unexpected, but good to be aware of
class parentclass {
public function getClass(){
echo get_class($this); //using "$this"
}
}
class child extends parentclass {
}
$obj = new child();
$obj->getClass(); //outputs "child"
class parentclass {
public function getClass(){
echo get_class(); //note, no "$this"
}
}
class child extends parentclass {
}
$obj = new child();
$obj->getClass(); //outputs "parentclass"`
davidc at php dot net
13-Oct-2005 10:25
`As of php5, you cannot use get_class($this); in a public static function. You would have to do something like this:
<?php
class BooBoof {
public static function getclass()
{
return __CLASS__;
}
}
$c = BooBoof::getclass();
print $c;
?>
To get the class since you cannot use
<?php
public static function getclass()
{
return get_class($this);
}
?>
Rather simple and straightforward but that might help some people that are searching for it..`
wired at evd dot ru
25-Sep-2005 02:25
`There is one unexpected bahaviour (for me as least):
<?php
class parent
{
...
public function getInstance ($id)
{
...
print get_class() . "\n" . __CLASS__;
...
}
}
class child extends parent
{
...
}
child::getInstance(...);
?>
This code will produce:
parent
parent
So I can't make "new $className(...)" in getInstance(). The only option is to do a fabric.`
kunxin at creaion dot com
25-Jul-2005 05:30
`I just migrated from PHP 4 to PHP 5 and noticed that in PHP 5.03 that a lot of code dependent on get_class() and its variants stop working.
It turns out that get_class() and its variants are now case-sensitive.`
refrozen dot com
05-Jul-2005 03:01
`philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns`
MagicalTux at FF.ST
02-Feb-2004 04:11
`Note that the constant __CLASS__ is different from get_class($this) :
<?
class test {
function whoami() {
echo "Hello, I'm whoami 1 !\r\n";
echo "Value of __CLASS__ : ".__CLASS__."\r\n";
echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
}
}
class test2 extends test {
function whoami2() {
echo "Hello, I'm whoami 2 !\r\n";
echo "Value of __CLASS__ : ".__CLASS__."\r\n";
echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
parent::whoami(); // call parent whoami() function
}
}
$test=new test;
$test->whoami();
$test2=new test2;
$test2->whoami();
$test2->whoami2();
?>
The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2
Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2
In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.`
Dan
29-Jan-2003 10:00
`This function does return the class name in lowercase, but that does not seem to make any difference. The code below, although very sloppy, works fine in all of the following configurations.
PHP 4.2.2 on Windows NT5 with Apache 1.3.24
PHP 4.2.1 in Zend Development Environment on box above
PHP 4.2.3 on Linux RedHat 7.3 with Apache 1.3.27
class TeSt {
var $a;
var $b = "Fred";
// Notice the case difference in the constructor name
function Test() {
$classname = get_class($this); // $classname = "test"
$this->ra = get_class_vars($classname);
}
}
// Next line also works with Test(), TEST(), or test()
$obj = new TeSt();
print_r($obj->ra);
Result :
Array
(
[a] =>
[b] => Fred
)`
oliver DOT pliquett @mediagear DOT de
13-Aug-2002 08:07
`This function can become _VERY_ helpful if you want to return a new object of the same type. See this example:
<?php
class Foo{
var $name;
function Foo( $parameter ){
$this->name = $parameter;
}
function whoami() {
echo "I'm a " . get_class( $this ) ."\n";
}
function getNew() {
$className = get_class( $this );
// here it happens:
return new $className ( "world" ) ;
}
}
class Bar extends Foo {
function Bar( $name ){
$this->Foo( $name );
}
function welcome() {
echo "Hello, " . $this->name . "! \n";
}
}
// We generate a Bar object:
$myBar = new Bar( "Oliver" );
$myBar->welcome();
//now let's instanciate a new Bar object.
//note: this method is inherited from Foo by Bar!
$baba = $myBar->getNew();
$baba->welcome();
$baba->whoami();
/* Output:
Hello, Oliver!
Hello, world!
I'm a bar
*/
?>`
philip at cornado dot com
20-Jun-2002 12:15
`As of PHP 4.3.0 the constant __CLASS__ exists and contains the class name.`
add a note
get_declared_classes get_class_vars

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST