Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

get_class()

Given an object, get_class returns its actual class name, including the namespace and without a leading backslash.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

get_class(object $object = ?): string

Given an object, get_class returns its actual class name, including the namespace and without a leading backslash. An inherited method inspecting $this therefore sees the concrete subclass. Supplying a class-name string instead of an object raises TypeError. The parameterless form inside a class is deprecated since PHP 8.3 and refers to the declaring scope. Calling it without an argument inside a method emits E_DEPRECATED and returns its declaring class. Outside a class the argumentless call throws Error.

Signature

get_class(object $object = ?): string

Example output

Guide\Detail
TypeError
deprecated Guide\BaseRow
Error

Examples

<?php
namespace Guide;
class BaseRow {
    public function name(): string { return get_class($this); }
    public function declared(): string { return get_class(); }
}
class Detail extends BaseRow {}
echo (new Detail())->name(), PHP_EOL;
try { get_class(Detail::class); } catch (\TypeError $e) { echo get_class($e), PHP_EOL; }
set_error_handler(static function (int $level): bool {
    echo $level === E_DEPRECATED ? "deprecated " : "other ";
    return true;
});
try { echo (new Detail())->declared(), PHP_EOL; } finally { restore_error_handler(); }
try { get_class(); } catch (\Error $e) { echo get_class($e); }

Result

Guide\Detail
TypeError
deprecated Guide\BaseRow
Error

Sources