How to get class name without namespace in PHP

藏色散人
Release: 2023-04-08 07:34:02
forward
2919 people have browsed it

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

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

basename(str_replace('\\', '/', $class));
Copy after login

substr 实现

substr(strrchr($class, "\\"), 1);
// or
substr($class, strrpos($class, '\\') + 1);
Copy after login

explode 实现

array_pop(explode('\\', $class));
Copy after login

ReflectionClass 实现

(new \ReflectionClass($class))->getShortName();
Copy after login

其中,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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!