Back to results for “OOP”
PHP › Namespaces & Autoloading

What is the difference between using a relative namespace reference, a fully qualified name starting with a backslash, and importing a class with use, when referencing a class from within a namespaced file?

Intermediate

Answer

Within a namespaced file, referencing a class name without any prefix is interpreted relative to the current namespace, a fully qualified name starting with a leading backslash always refers to that exact global path regardless of the current namespace, and using the use keyword to import a class lets you refer to it by its short name as if it were local, with each approach being appropriate in slightly different situations depending on whether you need to reference something within the current namespace, something entirely unrelated, or something you plan to use repeatedly throughout the file.
namespace App\Services;

use App\Models\User;

class Mailer {
    public function send(User $user) {
        $logger = new \App\Logging\Logger();
    }
}
Real-world example A developer writing a class within the App\Services namespace imports the User model using use for repeated convenient reference, while using a fully qualified name with a leading backslash for a Logger class only referenced once, avoiding an unnecessary import for a single usage.

Common follow-ups: Why does a fully qualified class name always start with a leading backslash?;When is it appropriate to use a fully qualified name instead of importing a class with use?