get_called_class

(PHP 5 >= 5.3.0)

get_called_classИмя класса, полученное с помощью позднего статического связывания

Описание

string get_called_class ( void )

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

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

Возвращает имя класса. Возвращает FALSE, если было вызвано вне класса.

Примеры

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

<?php

class foo {
    static public function 
test() {
        
var_dump(get_called_class());
    }
}

class 
bar extends foo {
}

foo::test();
bar::test();

?>

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

string(3) "foo"
string(3) "bar"

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

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

Коментарии

It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function 
__construct() {
    }

    final public static function 
getInstance() {
        static 
$aoInstance = array();

       
$calledClassName get_called_class();

        if (! isset (
$aoInstance[$calledClassName])) {
           
$aoInstance[$calledClassName] = new $calledClassName();
        }

        return 
$aoInstance[$calledClassName];
    }

    final private function 
__clone() {
    }
}

class 
DatabaseConnection extends Singleton {

    protected 
$connection;

    protected function 
__construct() {
       
// @todo Connect to the database
   
}

    public function 
__destruct() {
       
// @todo Drop the connection to the database
   
}
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn DatabaseConnection::getInstance();  // Returns single instance
?>
2008-10-08 15:00:59
http://php5.kiev.ua/manual/ru/function.get-called-class.html
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class {
    public function 
get_class_tree(){
       
$cur_class get_called_class();
        do {
            echo 
$cur_class;           
        }
        while(
$cur_class get_parent_class($cur_class));
    }
}

class 
{

}

class 
{

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
2009-02-21 12:03:17
http://php5.kiev.ua/manual/ru/function.get-called-class.html
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class {
  function 
getXName() {
     return 
x::getClassName();
  }
  function 
getXStaticName() {
     return 
x::getStaticClassName();
  }

}

class 
extends {
}

class 
{
  public function 
getClassName() {
    return 
get_called_class();
  }
  public static function 
getStaticClassName() {
    return 
get_called_class();
  }
}

$a = new a();

$b = new b();

echo 
$a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
2009-08-07 09:53:03
http://php5.kiev.ua/manual/ru/function.get-called-class.html
Автор:
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function 
test() {
   
var_dump(get_called_class());
  }
 
  public function 
testTwo() {
   
var_dump(get_called_class());
  }
}

class 
bar extends foo {
}

class 
abc {
  function 
test() {
   
foo::test();
   
bar::test();
  }
 
  function 
testTwo() {
   
foo::testTwo();
   
bar::testTwo();
  }
}

echo 
"basic\n";
foo::test();
bar::test();

echo 
"basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo 
"in a class\n";
$abc = new abc();
$abc->test();

echo 
"in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
2009-10-28 22:41:34
http://php5.kiev.ua/manual/ru/function.get-called-class.html
Автор:
SEE: language.oop5.late-static-bindings

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php 
static::$foo;
?>

versus
<?php
$that
=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as 
<?php 
static::$foo//and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
2011-04-06 12:14:44
http://php5.kiev.ua/manual/ru/function.get-called-class.html
get_called_class() in closure-scopes:

<?PHP
   
ABSTRACT CLASS Base
   
{
        protected static 
$stub = ['baz'];
       
       
//final public function boot()
       
static public function boot()
        {
            print 
__METHOD__.'-> '.get_called_class().PHP_EOL;
           
           
array_walk(static::$stub, function()
            {
                print 
__METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }
       
        public function 
__construct()
        {
           
self::boot();
            print 
__METHOD__.'-> '.get_called_class().PHP_EOL;
           
           
array_walk(static::$stub, function()
            {
                print 
__METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }
    }
   
    CLASS 
Sub EXTENDS Base
   
{
    }
   
   
// static boot
       
Base::boot(); print PHP_EOL;
           
// Base::boot        -> Base
            // Base::{closure}    -> Base
           
       
Sub::boot(); print PHP_EOL;
           
// Base::boot        -> Sub
            // Base::{closure}    -> Base
           
       
new sub;
           
// Base::boot        -> Sub
            // Base::{closure}    -> Base
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub
   
    // instance boot
       
new sub;
           
// Base->boot        -> Sub
            // Base->{closure}    -> Sub
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub
?>
2013-02-05 17:09:30
http://php5.kiev.ua/manual/ru/function.get-called-class.html
Автор:
As of PHP 5.5 you can also use "static::class" to get the name of the called class.

<?php
class Bar {
    public static function 
test() {
       
var_dump(static::class);
    }
}

class 
Foo extends Bar {

}

Foo::test();
Bar::test();
?>

Output:

string(3) "Foo"
string(3) "Bar"
2014-09-24 10:00:40
http://php5.kiev.ua/manual/ru/function.get-called-class.html
When calling dynamic method statically in php 5.6 (under 7) it allows it, but it doesnt work, it incorrectly evaluates class that called our subject class, therefore containing method must be static.
2017-09-12 18:57:20
http://php5.kiev.ua/manual/ru/function.get-called-class.html
namespace root;
class Factor {
    protected static $instance = null;

    private function __construct() {

    }

    public static function getInstance() {
        if (!self::$instance) {
            $name           = get_called_class();
            self::$instance = new $name();
        }

        return self::$instance;
    }
}

namespace admin\test;

use root\Factor;

class Single extends Factor {
    public function abc() {
        return 'abc';
    }
}

namespace index;

use admin\test\Single;

class Index {
    public function get() {
        return Single::getInstance();
    }
}

$index = new Index();
var_dump($index->get());

The result is:

object(admin\test\Single)#2 (0) {
}
2020-03-24 09:08:18
http://php5.kiev.ua/manual/ru/function.get-called-class.html

    Поддержать сайт на родительском проекте КГБ