Current Location: Home> Latest Articles> How to Get a Class Name Without Namespace in PHP

How to Get a Class Name Without Namespace in PHP

gitbox 2025-07-30

What is a Namespace

Before diving into how to get a class name without a namespace, let's first understand what namespaces are in PHP.

Namespaces are a feature introduced in PHP 5.3, allowing the same class name to exist in different files without conflict. With namespaces, developers can better organize and manage code, especially when building large applications.

Using Namespaces

In PHP, namespaces are defined using the namespace keyword. We can define a namespace for our program using namespace, as shown below:

namespace my_namespace;

You can also define multiple namespaces within the same file, like this:

namespace my_namespace1;
namespace my_namespace2;

If a class is defined within a namespace, you need to use the full class name path to reference it:

new my_namespace\MyClass();

You can simplify referencing classes within namespaces by using the use keyword:

use my_namespace\MyClass;
$obj = new MyClass();

Getting a Class Name Without Namespace

Sometimes, we need to get a class name without its namespace. In this case, we can use the built-in PHP function class_basename() to retrieve it.

class_basename()

The class_basename() function extracts the part of a class name that does not include the namespace.

$className = class_basename('App\Http\Controllers\Controller');
// $className will be 'Controller'

Note that class_basename() is only applicable to class names with namespaces. If you want to get a class name without the namespace, make sure to use class_exists() first to verify the class exists, then use class_basename() to retrieve the name.

get_class()

Another way to get a class name without the namespace is by using the get_class() function.

$obj = new MyClass();
$className = get_class($obj);
// $className will be 'MyClass'

When using get_class(), you need to pass an object of the class, not the class name as a string. This method is only suitable for getting class names without the namespace.

Summary

This article introduced the concept of namespaces and how to use them in PHP. We also discussed two common methods for getting a class name without a namespace: class_basename() and get_class(). Hopefully, this guide will help developers manage classes and namespaces more efficiently in PHP.