PHP 获取不带命名空间的类名

方法很多,列出几个,以供参考。

  • Laravel 源码里扒出来的 class_basename 辅助函数

    basename(str_replace('\\', '/', $class));
  • substr 实现

    substr(strrchr($class, "\\"), 1);
    // or
    substr($class, strrpos($class, '\\') + 1);
  • explode 实现

    array_pop(explode('\\', $class));
  • ReflectionClass 实现

    (new \ReflectionClass($class))->getShortName();

其中,ReflectionClass 是最快最保险的方案,但此类必须实际存在,不存在则会抛出 ReflectionException: Class \Foo\Bar does not exist

本作品采用《CC 协议》,转载必须注明作者和本文链接
Former WinForm and PHP engineer. Now prefer Golang and Rust, and mainly working on DevSecOps and Kubernetes.
本帖由系统于 4年前 自动加精
讨论数量: 1

还有 get_class

4年前 评论
鱼咸 4年前
MuYan 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
67
粉丝
590
喜欢
1235
收藏
1133
排名:13
访问:32.4 万
私信
所有博文
社区赞助商