Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Name Resolution Rules
In PHP, namespace resolution follows specific rules that determine how the interpreter locates classes, functions, and constants. Understanding these rules is crucial for writing maintainable code with proper namespace organization.
Types of Namespace Names
PHP recognizes three types of namespace identifiers −
Unqualified names − Names without namespace separator (
\). They refer to the current namespace.Qualified names − Names containing separator symbol like
myspace\space1. These resolve to subnamespaces.Fully qualified names − Names starting with
\character like\myspace\space1. These resolve to absolute namespaces.
Resolution Rules
Unqualified Names
Names without separators refer to the current namespace −
<?php
namespace MySpace;
class MyClass {
public function test() {
return "From MySpace namespace";
}
}
// Unqualified name - refers to MySpace\MyClass
$obj = new MyClass();
echo $obj->test();
?>
From MySpace namespace
Qualified Names
Names with separators resolve to relative namespaces −
<?php
namespace MySpace\SubSpace {
class Helper {
public static function getName() {
return "SubSpace Helper";
}
}
}
namespace MySpace {
// Qualified name - refers to MySpace\SubSpace\Helper
echo SubSpace\Helper::getName();
}
?>
SubSpace Helper
Fully Qualified Names
Names starting with \ resolve to absolute namespaces −
<?php
namespace Global\Space {
class Calculator {
public static function add($a, $b) {
return $a + $b;
}
}
}
namespace Different\Space {
// Fully qualified name - absolute reference
$result = \Global\Space\Calculator::add(5, 3);
echo "Result: " . $result;
}
?>
Result: 8
Import Rules
PHP uses import tables to translate names. The first segment of qualified names is translated according to current import rules −
<?php
namespace App\Models {
class User {
public static function getType() {
return "User Model";
}
}
}
namespace App\Controllers {
use App\Models as M;
// 'M' is translated to 'App\Models' via import table
echo M\User::getType();
}
?>
User Model
Function and Constant Resolution
For unqualified function and constant names outside global namespace, PHP performs fallback resolution −
<?php
namespace TestSpace;
function strlen($str) {
return "Custom strlen: " . \strlen($str);
}
// First looks for TestSpace\strlen, then global strlen
echo strlen("Hello");
echo "
";
// Explicitly call global function
echo \strlen("Hello");
?>
Custom strlen: 5 5
Conclusion
PHP namespace resolution follows predictable rules based on name qualification. Unqualified names use current namespace, qualified names are relative, and fully qualified names are absolute. Understanding these rules helps avoid naming conflicts and creates cleaner code organization.
