Home  >  Article  >  Backend Development  >  How to get class name without namespace in PHP

How to get class name without namespace in PHP

藏色散人
藏色散人forward
2020-01-06 16:32:593073browse

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

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。

更多PHP相关知识,请访问PHP教程

The above is the detailed content of How to get class name without namespace in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete