Concept Flow - Namespace declaration syntax
Start PHP file
Declare namespace
Write code inside namespace
Use code with namespace
End of file
This flow shows how a PHP file starts, declares a namespace, contains code inside it, and ends.
<?php namespace MyApp\Utils; function greet() { return "Hello"; }
| Step | Code Line | Action | Namespace Context | Result |
|---|---|---|---|---|
| 1 | <?php | Start PHP code | Global | PHP interpreter starts reading |
| 2 | namespace MyApp\Utils; | Declare namespace | MyApp\Utils | Namespace set to MyApp\Utils |
| 3 | function greet() { return "Hello"; } | Define function | MyApp\Utils | Function greet() defined inside namespace |
| 4 | ?> | End PHP code | MyApp\Utils | PHP interpreter stops reading |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| Namespace | Global | MyApp\Utils | MyApp\Utils | MyApp\Utils |
| Function greet | Not defined | Not defined | Defined in MyApp\Utils | Defined in MyApp\Utils |
PHP Namespace Declaration Syntax: - Use 'namespace Name;' at the top of PHP file - Declares a namespace for all code below - Functions/classes inside belong to that namespace - Helps avoid name conflicts - Must be declared before any code except declare or strict types
namespace to declare namespaces at the top of a file.namespace MyApp; with a semicolon at the end.namespace MyApp\Utils;.<?php
namespace App\Tools;
class Helper {
public static function greet() {
return 'Hello from Helper';
}
}
use App\Tools\Helper;
echo Helper::greet();
?>use statement imports it so we can call Helper directly.Helper::greet() returns the string 'Hello from Helper'.<?php
namespace MyApp\Utils
class Logger {}
?>namespace MyApp\Utils.Company\Project\Module in one PHP file. Which is the correct way to do this?namespace Company\Project\Module;
class Feature {} correctly declares nested namespaces with backslashes and a semicolon. Separate declarations like namespace Company;
namespace Project;
namespace Module;
class Feature {} place the class in top-level Module, not nested under Company\Project. Using forward slashes or dots as separators is invalid.Pass the test and this pattern moves unknown