Namespaces and Module Systems
PHP namespace/use resolution and aliasing, surveyed against Go, Java, Rust, Python and JS module systems; links to spl_autoload_register.
C C23
#include <stdio.h>
/* C predates module systems: headers + the linker play the role; the
convention is a name prefix as the "namespace" */
typedef struct {
const char *name;
} User;
const char *user_greet(const User *u); /* declaration: the "header" part */
static char buf[64];
const char *user_greet(const User *u) { /* definition: the "impl" part */
snprintf(buf, sizeof(buf), "Hello, %s", u->name);
return buf;
}
int main(void) {
User u = {"Alice"};
printf("%s\n", user_greet(&u)); /* the prefix is the namespace */
return 0;
}
Hello, Alice
C++ C++26
#include <cstdio>
#include <string>
#include <utility>
// C++ has real namespaces; deployment still rides on headers + linking
// (C++20 added language-level modules, headers remain dominant)
namespace App::Models { // nested namespace (C++17 syntax)
class User {
public:
std::string name;
explicit User(std::string n) : name(std::move(n)) {}
std::string greet() const { return "Hello, " + name; }
};
}
int main() {
App::Models::User u{"Alice"}; // fully qualified
namespace models = App::Models; // namespace alias (like use ... as ...)
models::User q{"Bob"};
std::printf("%s\n", u.greet().c_str());
std::printf("%s\n", q.greet().c_str());
return 0;
}
Hello, Alice Hello, Bob
C# v11.0.100
using App.Models; // using: import a namespace
var u = new User("Alice"); // unqualified, resolved via using
Console.WriteLine(u.Greet());
Console.WriteLine(typeof(User).FullName ?? ""); // the fully qualified name
namespace App.Models { // the namespace declaration
class User {
public User(string name) { Name = name; }
public string Name { get; }
public string Greet() => "Hello, " + Name;
}
}
Hello, Alice App.Models.User
Go v1.27.4
package main // every Go file declares its package: the namespace unit
import (
"fmt"
str "strings" // import with an alias (like use ... as ...)
)
func main() {
fmt.Println(str.ToUpper("abc")) // aliased import, qualified access
fmt.Println(fmt.Sprintf("%s=%d", "pkg", 1)) // package name + symbol
}
ABC pkg=1
Java v27.0.1
import java.util.List; // import: a single type
import static java.util.List.of; // static import: members directly
public class Main {
public static void main(String[] args) {
List<String> a = of("x", "y"); // via static import
java.util.Map<String, Integer> m = new java.util.HashMap<>(); // fully qualified: no import
m.put("n", a.size());
System.out.println(a + " " + m);
}
}
[x, y] {n=2}
JavaScript v26.13.1
// JS modules are files (ESM import/export); inside a single script the older
// namespace-object idiom shows the same idea
const App = {
Models: {
User: class {
constructor(name) { this.name = name; }
greet() { return "Hello, " + this.name; }
},
},
};
const { User } = App.Models; // destructuring import (like use App\Models\User)
console.log(new User("Alice").greet());
console.log(new App.Models.User("Bob").greet()); // fully qualified access
Hello, Alice Hello, Bob
PHP v8.6.0
namespace App\Models { // declare: symbols below live under App\Models
class User {
public function __construct(public string $name) {}
public function greet(): string { return "Hello, " . $this->name; }
}
}
namespace App\Controllers {
use App\Models\User; // import: unqualified "User" now resolves here
$u = new User("Alice"); // unqualified name, resolved via the use statement
echo $u->greet(), "\n";
echo User::class, "\n"; // ::class reveals the fully qualified name
$q = new \App\Models\User("Bob"); // fully qualified: no import needed
echo $q->greet(), "\n";
}
Hello, Alice App\Models\User Hello, Bob
Python v3.15.2
# Python: the module (file) IS the namespace; import binds names into scope
import json as j # module import + alias (like use ... as ...)
from collections import OrderedDict # import one member directly
tags = OrderedDict([("kind", "syntax")])
print(j.dumps(tags)) # aliased module, qualified access
print(type(tags).__module__) # introspection: the defining module's name
{"kind": "syntax"}
collections
Rust v1.99.1
// Rust: mod declares a module (the namespace unit); use brings paths in
mod models {
pub struct User {
pub name: String,
}
impl User {
pub fn greet(&self) -> String {
format!("Hello, {}", self.name)
}
}
}
use models::User; // the import; pub is required to be visible outside
fn main() {
let u = User { name: "Alice".to_string() };
println!("{}", u.greet());
let q = crate::models::User { name: "Bob".to_string() }; // fully qualified path
println!("{}", q.greet());
}
Hello, Alice Hello, Bob
TypeScript v26.13.1
// Real-world TS organizes code with ESM files (import/export); the older
// namespace keyword needs a full compiler (tsc) and cannot run under Node's
// type-stripping runner, so the module-object idiom stands in here
const App = {
Models: {
User: class {
name: string;
constructor(name: string) {
this.name = name;
}
greet(): string {
return "Hello, " + this.name;
}
},
},
};
const { User } = App.Models; // destructuring import (like use App\Models\User)
console.log(new User("Alice").greet());
console.log(new App.Models.User("Bob").greet()); // fully qualified access
Hello, Alice Hello, Bob
Language differences
C: from before module systems (example): header declarations plus the linker merging object files play the module role; the "namespace" is a naming-prefix convention (user_greet in the example); static provides internal linkage.
C++: real namespaces exist: namespace declarations (nested App::Models and a namespace alias in the example) plus using declarations/directives; deployment still rides on headers + linking; C++20 added language-level modules (import) while headers remain mainstream.
C#: namespace + using (example): declaration and import are separate, typeof(T).FullName introspects the fully qualified name; file-scoped namespaces and global usings are the modern conventions.
Go: the package is the module unit (example): the directory is the package path, imports take aliases (str in the example); uppercase exports, lowercase stays private — visibility is built into the naming system; go.mod manages module versions.
Java: package + import (example, including static import): package names must match the directory layout; visibility spans public/protected/package-private.
JavaScript: ES modules with import/export (the file is the module), supporting import { a as b } renaming and import * as ns namespace imports; a single script simulates it with object literals (example); paths are resolved by bundlers/loaders.
PHP: namespace declarations plus use imports (example): classes/interfaces/functions/constants live under namespaces while variables do not; unqualified/qualified/fully-qualified resolution (the filesystem analogy); use ... as aliasing and ::class introspection; it pairs with spl_autoload_register: autoloading finds files by FQN — the namespace is the key of PSR-4 directory mapping.
Python: the module is the file (example): import / from...import / as aliasing; type(x).__module__ introspects the defining module (example); a package is a directory with __init__.py.
Rust: mod declares a module (example): private by default, pub to expose; use brings paths in and crate:: starts from the root; visibility is stricter than most (parents do not automatically see children).
TypeScript: real-world TS uses ESM (same as JS); the namespace keyword needs a full compiler (tsc) to transform and cannot run under Node's type-stripping runner, so the example uses the module-object idiom; import type gives type-only imports with zero runtime cost.