PHP Medium · Lesson 1 · On the house

Namespaces and use

namespace, use, FQCN, \ root. Lesson 1 is free — on the house.

Lessons · PHP Medium · Lesson 1 of 10 · On the house

Namespaces and use

namespace, use, FQCN, \ root.

Illustration for PHP
Lesson 1 is on the house.

namespace App\Models; at the top of a file puts every class, interface, trait, and function declared in that file into that namespace. Nested segments use \ — PHP's namespace separator, not a filesystem path by itself.

Inside a namespaced file, an unqualified new User() means App\Models\User if you are in App\Models. To reach the global root explicitly, prefix with a leading backslash: \Exception is the built-in Exception in the global namespace.

use App\Models\User; imports a short name into the current file so you can write new User() instead of the fully qualified class name (FQCN) \App\Models\User every time. use App\Models\User as Member; aliases the short name.

FQCN always starts from the root when written with a leading \, or is absolute relative to the declared namespace when you write App\Models\User from global code. Match the still's namespace, use, and which name you construct.

Misses: using / instead of \ in namespace names, forgetting the leading \ when you meant a global class from inside a namespace, or putting use below code that already referenced the short name.

namespaces

<?php
namespace App\Models;

use App\Support\Clock;

class User {
    public function __construct(public string $name) {}

    public function stamp(): string {
        return Clock::now() . ":" . $this->name;
    }
}

namespace App\Support;

class Clock {
    public static function now(): string {
        return "t0";
    }
}

namespace {
    use App\Models\User;
    $u = new User("Ada");
    echo $u->stamp() . "\n";
}
Match this when you type.

Quiz

What does namespace App\Models; do?

Quiz

How do you refer to global Exception from inside a namespace?

Quiz

What does use App\Models\User; enable?

Quiz

What is an FQCN?

Check

Match the still for: Namespaces and use.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.