How do I get an object's unqualified (short) class name?
In modern PHP development, namespaced classes are the norm. While get_class($object) is a convenient utility for debugging or type checking, it returns the fully qualified class name (FQCN), including the namespace. If you need to compare classes against a simple identifier like 'Name' rather than '\MyNamespace\Library\Entity\Contract\Name', you are looking for the "unqualified" or short class name.
The most direct solution is to extract the final component from the string returned by get_class(). Since PHP namespaces function as directory structures in the codebase, the last segment of the FQCN represents the actual class definition. You can achieve this using standard string manipulation functions like explode() and array_pop(), or more concisely with basename().
Extracting the Short Name via String Manipulation
The most robust approach without relying on external libraries is to treat the FQCN as a path-like string. Consider an object defined in the namespace Library\Entity\Contract named Name. The full string returned by get_class() looks like this:
'Library\Entity\Contract\Name'
To isolate just Name, you can split the string by the backslash delimiter and take the last element. This method is explicit and easy to understand, but it requires handling the array result.
$fqcn = get_class($object);
$shortName = explode('\\', $fqcn)[count(explode('\\', $fqcn)) - 1];
While this works, it is verbose. PHP offers a cleaner alternative using basename(). This function behaves similarly to how you would strip a directory path to get the filename. When applied to an FQCN, it effectively strips the namespace prefix and returns the class name.
$fqcn = get_class($object);
$shortName = basename($fqcn, '\\'); // Note: basename usually handles the delimiter internally in this context
// Or more strictly ensuring we strip the trailing backslash if present in some edge cases,
// though typically basename('Namespace\\ClassName', '\\') returns 'ClassName' directly.
// The most idiomatic way often looks like this:
$shortName = basename($fqcn); // Works well for FQCN as it treats the namespace as a directory path
Actually, basename() works natively with the backslash delimiter in PHP when dealing with FQCNs effectively acting as paths. A cleaner implementation is simply:
$shortName = basename(get_class($object));
If you need to perform a strict comparison against a specific short name, this approach allows your conditional logic to remain clean:
if (basename(get_class($object)) === 'Name') {
// ... do this
}
The Regex Alternative
The source material suggests using regular expressions as an option. While regex is powerful, it introduces unnecessary complexity for a task solvable with string functions. A pattern like '/^(.+\\\\)([A-Z][a-zA-Z]*)$/' could capture the last capitalized word, but it fails if the class name itself contains numbers or underscores (e.g., User_1). Furthermore, regex adds overhead to every object check. Unless you are processing massive streams of data where string function performance becomes a bottleneck, sticking to basename() is the pragmatic choice for maintainability and readability.
Trade-offs and Dynamic Namespaces
One might argue that using get_class($object) locks you into the FQCN structure. You are correct that hardcoding 'Library\Entity\Contract\Name' prevents dynamic namespace changes. However, deriving the short name dynamically ensures your logic adapts if you refactor the project hierarchy. If you move the class to a different directory, the string manipulation automatically yields the new short name without updating every conditional block in your codebase.
There is a caveat, however: this technique relies on the assumption that the class name itself does not contain backslashes (which is impossible for valid PHP identifiers) and that the naming convention follows standard PascalCase. If you are dealing with legacy code where classes might be named My_Class, basename() still works correctly because it treats the string as a path, splitting at the backslash boundaries regardless of the final character casing or content, provided the delimiter is the namespace separator.
When to Use Short Names vs. FQCNs
While extracting the short name solves the immediate problem, consider if you actually need to compare class names at runtime. In Laravel and modern PHP frameworks, type hints are preferred for defining behavior:
function processContract(Contract $contract) { ... }
This ensures that only objects of the Contract interface or class are passed, regardless of their namespace. If you must check the class identity dynamicallyâperhaps for logging, plugin registration, or legacy migration logicâusing basename(get_class($object)) provides a clean, non-breaking abstraction over the underlying namespaces. It keeps your conditionals focused on the entity rather than the location, which is exactly what you want when planning to change namespaces dynamically in the future.
