How to get all class names inside a particular namespace?
When you need to introspect a PHP application, specifically retrieving all classes registered under a specific namespace from outside that scope, the instinctive reaction is often get_declared_classes(). This function returns every user-defined class currently loaded in memory. However, as your source material demonstrates, simply calling this function inside a handler like ClassHandler will not automatically filter for only the MyNamespace classes if they are defined in separate files.
The core issue lies in PHP's autoloading mechanism and how namespaces interact with file inclusion. If MyClass1.php and MyClass2.php exist as physical files on your disk but have not been explicitly included or autoloaded into the current execution context, those classes simply do not exist in memory yet. Consequently, get_declared_classes() returns an empty list for them because they haven't been instantiated or referenced by the script engine.
To solve this, you must ensure the class files are actually loaded before querying the global symbol table. If your project is a standalone script, you have two primary strategies: manual file inclusion or utilizing an autoloader.
Manual File Inclusion
If you are building a tool or a legacy system where you control the file structure and want to avoid setting up complex autoloaders, you can explicitly include the relevant files. This is often necessary when dealing with static analysis tools or specific runtime environments where standard autoloading isn't configured.
You would iterate through your known list of files within the namespace directory and require them:
$namespacePath = '/path/to/MyNamespace';
$classFiles = array_filter(scandir($namespacePath), function ($file) {
return strpos($file, '.php') !== false && !str_starts_with($file, '.');
});
foreach ($classFiles as $file) {
require_once $namespacePath . '/' . $file;
}
$allClasses = get_declared_classes();
// Now filter for the specific namespace
$filteredClasses = array_filter($allClasses, function ($className) use ($namespace) {
return strpos($className, 'MyNamespace') === 0;
});
While effective, this approach is brittle. It assumes a flat directory structure and relies on file paths rather than class names. If your framework uses PSR-4 autoloading, manually including files breaks the encapsulation of that standard.
Using an Autoloader
In modern PHP development, especially within frameworks like Laravel or Symfony, classes are rarely loaded manually. Instead, they rely on spl_autoload_register to map namespaces to file paths dynamically. To get a list of declared classes in this environment, you cannot bypass the autoloader; you must trigger it.
The most robust way to achieve your goal is to instantiate at least one class from the target namespace. This forces the autoloader to resolve all its registered rules for that specific namespace, ensuring all dependent files are pulled into memory.
namespace SomethingElse;
use MyNamespace\MyClass1; // This triggers the autoloader
class ClassHandler {
public function getAllClasses() {
// Trigger autoload if necessary by instantiating a known class or using get_declared_classes
// after ensuring the environment has loaded the classes.
$allClasses = get_declared_classes();
// Filter for the specific namespace prefix
return array_filter($allClasses, function ($className) {
return str_starts_with($className, 'MyNamespace\\');
});
}
}
Note that str_starts_with is available in PHP 8.0+. If you are on an older version, use strpos($className, '\\MyNamespace\\') !== false.
Trade-offs and Pitfalls
A significant pitfall to consider is the distinction between "declared" and "instantiated." Calling get_declared_classes() only returns classes that have been loaded into memory. It does not return abstract classes, interfaces, or traits unless they are explicitly included. Furthermore, if you are running in a CLI environment with limited memory or as part of a large monolithic script, loading every class in a namespace might inadvertently trigger side effects defined in the __autoload logic of those specific files (e.g., database migrations or service registration).
Another edge case involves dynamic namespaces. If your classes utilize namespace MyNamespace; but are loaded via a custom autoloader that maps them differently, standard introspection might fail without understanding your specific autoloading configuration.
If you are working within the Laravel ecosystem, similar introspection can be helpful for generating documentation or auditing dependencies. In such cases, ensuring you have registered your autoloaders correctly is paramount before attempting to query the global class table. For advanced scaffolding or command-line tools where this logic resides, checking resources like https://laravelcompany.com can provide context on how frameworks manage their internal class registries and autoloading strategies, though the fundamental PHP mechanism remains get_declared_classes() combined with proper file loading.
Ultimately, there is no magic function that scans disk files and returns namespace names without loading them. You must either load the files explicitly or rely on your existing autoloader to populate memory before querying it.