get_class

get_class(object $object = ): string

返回对象所属的类名;与 instanceof 互为「类型问询」的两面:instanceof 回答是与否,get_class 给出确切名字。

C C23

C23
#include <stdio.h>

/* C 没有类——最接近的模式是结构体自带一个字符串「类名」标签 */
typedef struct {
    const char *kind; /* 手写的类名标签 */
} Object;

int main(void) {
    Object d = { "Dog" };
    Object a = { "Animal" };
    printf("%s\n", d.kind);
    printf("%s\n", a.kind);
    return 0;
}
输出
Dog
Animal

C++ C++26

C++26
#include <iostream>
#include <string>

class Animal {
public:
    virtual ~Animal() = default;
    virtual std::string name() const { return "Animal"; }
};

class Dog : public Animal {
public:
    std::string name() const override { return "Dog"; }
};

int main() {
    Dog d;
    Animal a;
    // typeid(d).name() 不可移植——符号名/实现定义,
    // 因此类名经由虚方法携带
    std::cout << d.name() << "\n";
    std::cout << a.name() << "\n";
    std::cout << (dynamic_cast<Dog*>(&d) != nullptr ? "yes" : "no") << "\n";
    return 0;
}
输出
Dog
Animal
yes

C# v11.0.100

v11.0.100
class Animal { }
class Dog : Animal { }

class MainClass {
    static void Main() {
        object d = new Dog();
        System.Console.WriteLine(d.GetType().Name);         // Dog
        System.Console.WriteLine(new Animal().GetType().Name);
        System.Console.WriteLine(d is Dog ? "yes" : "no"); // 是与否形态的对应
    }
}
输出
Dog
Animal
yes

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"reflect"
)

type Animal struct{}
type Dog struct{ Animal }

func main() {
	var d any = Dog{}
	fmt.Println(reflect.TypeOf(d).Name()) // Dog——裸类型名
	fmt.Println(fmt.Sprintf("%T", d))     // main.Dog——带包名
}
输出
Dog
main.Dog

Java v27.0.1

v27.0.1
class Animal { }
class Dog extends Animal { }

class Main {
    public static void main(String[] args) {
        Object d = new Dog();
        System.out.println(d.getClass().getSimpleName());  // Dog
        System.out.println(new Animal().getClass().getSimpleName());
        System.out.println(d instanceof Dog ? "yes" : "no");
    }
}
输出
Dog
Animal
yes

JavaScript v26.13.1

v26.13.1
class Animal {}
class Dog extends Animal {}

const d = new Dog();
console.log(d.constructor.name);            // Dog
console.log(new Animal().constructor.name); // Animal
console.log(d instanceof Dog ? "yes" : "no");
输出
Dog
Animal
yes

PHP v8.6.0

v8.6.0
class Animal {
    public function speak(): string { return "..."; }
}
class Dog extends Animal {
    public function speak(): string { return "Woof"; }
}

$d = new Dog();
echo get_class($d), "\n";            // Dog
echo get_class(new Animal()), "\n";  // Animal
echo $d instanceof Dog ? "yes" : "no", "\n";
// 8.3 起无参调用发出 E_DEPRECATED——类内请改用
// static::class 或 self::class
输出
Dog
Animal
yes

Python v3.15.2

v3.15.2
class Animal:
    pass


class Dog(Animal):
    pass


d = Dog()
print(type(d).__name__)           # Dog
print(type(Animal()).__name__)    # Animal
print("yes" if isinstance(d, Dog) else "no")
输出
Dog
Animal
yes

Rust v1.99.1

v1.99.1
// std::any::type_name 给出完整路径(如 "crate::Dog");
// 取最后一段得到裸类型名
struct Animal;
struct Dog;

fn bare_name<T>() -> &'static str {
    let full = std::any::type_name::<T>();
    full.rsplit("::").next().unwrap_or(full)
}

fn main() {
    println!("{}", bare_name::<Dog>());
    println!("{}", bare_name::<Animal>());
}
输出
Dog
Animal

TypeScript v26.13.1

v26.13.1
class Animal {}
class Dog extends Animal {}

const d = new Dog();
console.log(d.constructor.name); // Dog——运行期与 JS 相同
console.log(new Animal().constructor.name);
// 编译期加持:d 的静态类型是 Dog,判断按声明类校验
const cls: string = d.constructor.name;
console.log(cls === "Dog" ? "yes" : "no");
输出
Dog
Animal
yes

语言差异说明

C:无类与运行期类型信息——「对象类名」只能靠手写标签字段模拟(示例);要真运行期类型需自建注册表。

C++:typeid(d).name() 名字实现定义(如 MSVC 输出 class Dog、Itanium ABI 输出符号 3Dog),不可预置,故示例用虚方法携带名字;dynamic_cast 是「是否」形态的对应;std::type_index 可做哈希比较但名字仍不可移植。

C#:GetType().Name 是最贴近 get_class 的形态(示例);GetType().FullName 带命名空间(对应 PHP 无此区分,PHP 类名即全局名);is 运算符是 instanceof 对应。

Go:类型不是类——reflect.TypeOf(d).Name() 给裸名(示例);%T 给 main.Dog 带包名,等价于 PHP 的全限定名;非 any 静态变量直接 reflect.TypeOf 亦可。

Java:getClass().getSimpleName() 对应 get_class(示例);getName() 给全限定名(Main$Dog 形态会更复杂);与 instanceof 配对使用最常见。

JavaScript:d.constructor.name 是惯用形态(示例);注意 constructor 可被改写,原型链上 Object.getPrototypeOf(d).constructor.name 更严谨;类被 minify 后名字不可靠——生产环境勿依赖。

PHP:get_class($obj) 是对象类名的正统获取(示例);8.3 起无参调用发 E_DEPRECATED(类内改用 static::class);与 class_exists(查表)、is_a(判断)成族。

Python:type(d).__name__(示例);d.__class__.__name__ 等价;与 isinstance 配对;Python 类即对象,type(d) 直接可比较。

Rust:无继承无虚表,std::any::type_name::<T>() 是编译期泛型形态、给出完整路径(示例取末段得裸名);注意它仅用于调试,官方明示「格式可能变」——勿做逻辑判断。

TypeScript:运行期与 JS 一致(示例);编译期 d 的静态类型参与检查,d.constructor.name 的类型是 string 而非字面量——要字面量需断言。