In PHP the namespace is just a name added to every class construct and nothing else.
This is basically
class MyThing
the same as this namespace My;
class Thing
However namespaces was a pragmatic design choice that solved the community's problem with code organization and ever increasing project sizes and for that it worked pretty well because introducing namespaces didn't break any existing workflow.Today though I agree that proper module system would be nicer and now with PHP evolved even further it is perhaps time to introduce them.
Without having deep knowledge about PHP internals it feels like it would be possible to do because you can already today implement your own module system. Here is just something quick & dirty as a proof of concept.
module.php
<?php
return new class {
public const MY_CONST = 47;
private const MY_PRIVATE_CONST = 127;
// with PHP 8.1 you also have readonly properties
public string $myPublic = 'foo';
private int $myPrivate = 17;
public function helloWorld(string $name): void
{
echo "Hello, World {$name}!";
}
};
main.php <?php
final class ModuleException extends Exception {
}
function module(string $name): object
{
static $modules = [];
if (isset($modules[$name])) {
return $modules[$name];
}
try {
$module = @require $name;
} catch (Error $error) {
throw new ModuleException("No such module {$name}", 0, $error);
}
if (!is_object($module)) {
throw new ModuleException("Module {$name} is not an object");
}
$modules[$name] = $module;
return $module;
}
$my = module('module.php');
$my->helloWorld('Module system');
$other = module('module.php');
assert($my === $other);
The building block in PHP internals is the class - interfaces, traits and enums are all classes in disguise. Could it be possible to use classes for modules as well? Perhaps just add some syntactic sugar on top.