MENU
Namespaces
A namespace is used to prevent the name collisions of constants, functions, classes and interfaces. Its declaration must precede all other statements in a file, including any HTML code. The only statement that can precede it is the declare() statement used for the encoding directive.A namespace can take on the brace {} form, or the free statement form. However, the two different forms must not appear within a single file.
RESETRUNFULL
bar.php:
If a namespaced function or constant does not exist, PHP will automatically fall back to global functions or constants. On the other hand, class names always resolve to the current namespace.RESETRUNFULL
bar.php:
<?php //bar.php, namespaces in {} form
namespace Bar {
const a=10; // defined as \Bar\a
}
namespace {
const a=50; // defined as \a, in the global namespace
}
?>
<?php //foo.php, namespaces in free statement form
namespace Foo;
include "bar.php";
const a=20; // defined as \Foo\a;
echo a; // 20, resolves to \Foo\a
echo \Foo\a; // 20, resolves to \Foo\a
echo \Bar\a; // 10, resolves to \Bar\a
echo \a; // 50, resolves to \a, the global namespace
echo namespace\a; // 20, resolves to \Foo\a
//echo Foo\a; // error, resolves to \Foo\Foo\a
//echo Bar\a; // error, resolves to \Foo\Bar\a
namespace Foo\Alpha;
const a=30; // defined as \Foo\Alpha\a
echo a; // 30, resolves to \Foo\Alpha\a;
namespace Foo;
echo Alpha\a; // 30, resolves to \Foo\Alpha\a;
echo strlen("hi") // 2, fall back to \strlen(), the global nspc;
?>
<!DOCTYPE html>
<html>
<head></head>
<body><?php
include "foo.php";
echo a; // 50, resolves to \a
echo \Bar\a; // 10, resolves to \Bar\a
?>
</body>
</html>
We can use an alias for a class name, an interface name or a namespace.
A namespace can take on the brace {} form, or the free statement form. However, the two different forms must not appear within a single file.
RESETRUNFULL
alpha_beta.php:
foo-2.php:
RESETRUNFULL
alpha_beta.php:
<?php //alpha_beta.php
namespace Alpha\Beta;
class MyClass{
public static $v=100;
}
?>
foo-2.php:
<?php //foo2.php
namespace Foo;
include "alpha_beta.php";
$o=new \Alpha\Beta\MyClass;
$ns='Alpha\Beta\MyClass'; // no leading \ needed
$o2=new $ns;
echo $o2::$v;
use Alpha\Beta as A; // aliasing a namespace
echo A\MyClass::$v;
use Alpha\Beta\MyClass as C; // aliasing a class name
echo C::$v;
use Alpha\Beta\MyClass; // Alpha\Beta\MyClass as MyClass;
echo MyClass::$v;
use Alpha\Beta\MyClass as D, Alpha\Beta; // Multiple decl.
echo Beta\MyClass::$v;
?>
<!DOCTYPE html>
<html>
<head></head>
<body><?php
include "foo-2.php";
?>
</body>
</html>