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 Defining namespace
PHP namespaces provide a way to encapsulate and organize code by grouping related classes, functions, and constants. The namespace keyword must be declared as the very first statement in a PHP file, right after the opening <?php tag.
Syntax
The basic syntax for declaring a namespace is −
<?php namespace namespace_name; // Your code here ?>
Example
Here's a simple example of defining a namespace with a class and function −
<?php
namespace myspace;
class myclass {
public function display() {
echo "Class in myspace namespace<br>";
}
}
function hello() {
echo "Hello World<br>";
}
?>
Namespace Declaration Rules
If the namespace declaration is not at the top of the file, PHP throws a fatal error. The following example demonstrates this −
<?php
echo "Some code before namespace";
namespace myspace;
function hello() {
echo "Hello World<br>";
}
?>
PHP Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script
Exception with Declare Statement
Only the declare construct can appear before a namespace declaration −
<?php
declare(strict_types=1);
namespace myspace;
function hello() {
echo "Hello World<br>";
}
hello();
?>
Hello World
Key Points
- Namespace declaration must be the first statement after
<?php - Only
declarestatements can precede namespace declarations - No HTML, whitespace, or other PHP code can appear before namespace
- Namespaces help avoid naming conflicts and organize code logically
Conclusion
Proper namespace declaration is crucial for organizing PHP code. Always place the namespace statement immediately after the opening PHP tag to avoid fatal errors and maintain clean code structure.
