Namespace definition
The namespace is declared using namespace keyword, which should be at the very beginning of the file. Example:
Example#1 Defining namespace
<?php
namespace MyProject::DB;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
Namespace can contain class, constant and function definitions, but no free code.
Namespace definition does the following:
- Inside namespace, all class, function and constant names in definitions are automatically prefixed with namespace name. The class name is always the full name, i.e. in the example above the class is called MyProject::DB::Connection.
- Constant definitions create constant which is composed of namespace name and constant name. Like class constants, namespace constant can only contains static values.
-
Unqualified class name (i.e., name not containing ::) is resolved at runtime following this procedure:
- Class is looked up inside the current namespace (i.e. prefixing the name with the current namespace name) without attempting to autoload.
- Class is looked up inside the global namespace without attempting to autoload.
- Autoloading for name in current namespace is attempted.
- If previous failed, lookup fails.
-
Unqualified function name (i.e., name not containing ::) is looked up at runtime first in the current namespace and then in the global space.
-
Unqualified constant names are looked up first at current namespace and then among globally defined constants.