bhylu.com

Advertisements

PHP Namespaces

A namespace organises names and avoids accidental collisions. It does not automatically find or install the file containing a class.

How it works

A namespace declaration appears at the beginning of its file, after an allowed strict-types declaration. use can introduce an alias for a fully qualified name. Composer autoloading addresses how a class name is loaded from a project; it is separate from the namespace syntax itself. Avoid deriving include paths or arbitrary class names directly from request data.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l namespaces.php
php namespaces.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · namespaces.php

<?php
declare(strict_types=1);

namespace Bhylu\Lending;

class Reference { public function text(): string { return "Local reference"; } }
$value = new Reference();
echo $value->text(), "\n";
echo __NAMESPACE__, "\n";

Expected result

Local reference
Bhylu\Lending

The short class name resolves inside the declared namespace. The magic constant reports that namespace for this source context. All code is in one file here, so there is no autoloader to configure yet. In a project, a PSR-4 mapping and matching directory layout can make that loading relationship explicit.

Check the official PHP manual for detailed version and API contracts.