Using namespaces: Basics

(PHP 5 >= 5.3.0, PHP 7)
Examples:
file1.php

Here is an example of the three kinds of syntax in actual code:

1
2
3
4
5
6
7
8
9
10
<?php
namespace Foo\Bar\subnamespace;
 
const FOO = 1;
function foo() {}
class foo
{
    static function staticmethod() {}
}
?>

file2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
namespace Foo\Bar;
include 'file1.php';
 
const FOO = 2;
function foo() {}
class foo
{
    static function staticmethod() {}
}
 
/* Unqualified name */
foo(); // resolves to function Foo\Bar\foo
foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo FOO; // resolves to constant Foo\Bar\FOO
 
/* Qualified name */
subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,
                                  // method staticmethod
echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO
                                   
/* Fully qualified name */
\Foo\Bar\foo(); // resolves to function Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod
echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO
?>
Accessing global classes, functions and constants from within a namespace

Note that to access any global class, function or constant, a fully qualified name can be used, such as \strlen() or \Exception or \INI_ALL.

1
2
3
4
5
6
7
8
9
10
11
<?php
namespace Foo;
 
function strlen() {}
const INI_ALL = 3;
class Exception {}
 
$a = \strlen('hi'); // calls global function strlen
$b = \INI_ALL; // accesses global constant INI_ALL
$c new \Exception('error'); // instantiates global class Exception
?>
doc_php
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.