- Как получить имя вызывающего класса (в PHP)
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- get_called_class
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- See Also
- User Contributed Notes 9 notes
- get_called_class
- Parameters
- Return Values
- Examples
- See Also
- get_class
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Смотрите также
Как получить имя вызывающего класса (в PHP)
$callbacksClass должен быть администратором или клиентом. Или я пропустил здесь пункт целиком и должен пойти по этому пути? Следует отметить, что я буду принимать только ответ, который не требует, чтобы я отправил имя класса в качестве аргумента методу registerCallback.
ОТВЕТЫ
Ответ 1
$this->callbacks[$onAction][] = $callbackMethod; $className = get_class($this); // Call callback method $className->$callbackMethod();
Ответ 2
Если кто-нибудь пришел сюда, чтобы узнать, как получить имя вызывающего класса из другого класса, как я, проверьте это https://gist.github.com/1122679
EDIT: вложенный код
function get_calling_class() < //get the trace $trace = debug_backtrace(); // Get the class that is asking for who awoke it $class = $trace[1]['class']; // +1 to i cos we have to account for calling this function for ( $i=1; $i>
class A < function t() < echo get_calling_class(); >> class B < function x() < $a = new A; $a->t(); > > $b = new B; $b->x(); // prints B
Ответ 3
Вы действительно должны сделать что-то вроде:
$this->registerCallback(array($this, 'onTiny'), anActionType);
Так работает PHP с обработкой методов объектов.
get_called_class
Gets the name of the class the static method is called in.
Parameters
This function has no parameters.
Return Values
Errors/Exceptions
If get_called_class() is called from outside a class, an Error is thrown. Prior to PHP 8.0.0, an E_WARNING level error was raised.
Changelog
Version | Description |
---|---|
8.0.0 | Calling this function from outside a class, will now throw an Error . Previously, an E_WARNING was raised and the function returned false . |
Examples
Example #1 Using get_called_class()
class foo static public function test () var_dump ( get_called_class ());
>
>
The above example will output:
See Also
- get_parent_class() — Retrieves the parent class name for object or class
- get_class() — Returns the name of the class of an object
- is_subclass_of() — Checks if the object has this class as one of its parents or implements it
User Contributed Notes 9 notes
As of PHP 5.5 you can also use «static::class» to get the name of the called class.
class Bar public static function test () var_dump (static::class);
>
>
get_called_class() in closure-scopes:
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 ;
>);
>
>
// static boot
Base :: boot (); print PHP_EOL ;
// Base::boot -> Base
// Base:: -> Base
Sub :: boot (); print PHP_EOL ;
// Base::boot -> Sub
// Base:: -> Base
new sub ;
// Base::boot -> Sub
// Base:: -> Base
// Base->__construct -> Sub
// Base-> -> Sub
// instance boot
new sub ;
// Base->boot -> Sub
// Base-> -> Sub
// Base->__construct -> Sub
// Base-> -> Sub
?>
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
static:: $foo ;
?>
versus
$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
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.
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();
>
class Single extends Factor public function abc() return ‘abc’;
>
>
class Index public function get() return Single::getInstance();
>
>
$index = new Index();
var_dump($index->get());
get_called_class
Получает имя класса,в котором вызывается статический метод.
Parameters
Эта функция не имеет параметров.
Return Values
Возвращает имя класса. Возвращает false , если вызывается извне класса.
Examples
Пример # 1 Использование get_called_class ()
class foo < static public function test( ) < var_dump(get_called_class()); >> class bar extends foo < >foo::test(); bar::test(); ?>
Выводится приведенный выше пример:
See Also
- get_parent_class () — извлекает имя родительского класса для объекта или класса
- get_class () — возвращает имя класса объекта
- is_subclass_of () — Проверяет, имеет ли объект этот класс в качестве одного из своих родителей или реализует его
PHP 8.2
(PECL geoip 1.0.4)geoip_time_zone_by_country_and_region Возвращает для некоторого кода combo Функция geoip_time_zone_by_country_and_region()возвращает
(PHP 4, 5, 7, 8) get_browser Сообщает, на что способен пользователь Попытки определить возможности браузера пользователя путем поиска информации о браузере
(PHP 4,5,7,8)get_cfg_var Получает значение параметра конфигурации PHP Эта функция не возвращает информацию о конфигурации,установленную при компиляции PHP,
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 ();
Результат выполнения данного примера:
Its name is foo My name is foo
Пример #2 Использование get_class() в родительском классе
abstract class bar public function __construct ()
var_dump ( get_class ( $this ));
var_dump ( get_class ());
>
>
Результат выполнения данного примера:
Смотрите также
- get_called_class() — Имя класса, полученное с помощью позднего статического связывания
- get_parent_class() — Возвращает имя родительского класса для объекта или класса
- gettype() — Возвращает тип переменной
- is_subclass_of() — Проверяет, содержит ли объект в своем дереве предков указанный класс