Introduction
Declaration of class, function and constants inside a namespace affects its acess, although any other PHP code can be present in it. PHP's namespace keyword is used to declare a new namespace. A file with .php extension must have namespace declaration in very first line after <?php tag, before any other code such as HTML script.
Example
<?php
namespace myspace;
class myclass{
//
}
function hello() {
echo "Hello World\n";
}
?>If namespace declaration is not at the top of file, PHP parser throws fatal error
Example
<html>
<body>
Hello world
<?php
namespace myspace;
function hello() {
echo "Hello World\n";
}
use myspace;
myspace\hello();
?>
</body>
</html>
?>Output
Above code now returns name following error
PHP Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script
Only declare construct can appear before namespace declaration
Example
<?php
declare (strict_types=1);
namespace myspace;
function hello() {
echo "Hello World\n";
}
use myspace;
myspace\hello();
?>