PHP Namespaces

PHP Namespaces



A namespace in PHP is a way to organize and group related code (like classes, interfaces, functions, or constants) and prevent name conflicts between parts of your application or with external libraries.


Why Use Namespaces?

1. Avoid Name Collisions

If two classes have the same name (e.g., User), a namespace separates them.

2. Organize Code

Helps maintain a clean and modular codebase, especially in large projects or frameworks like Laravel, Symfony, etc.



Namespaces are declared at the beginning of a file using the namespace keyword:


Syntax


<?php
  namespace Html;
?>

Note

The namespace must be declared at the very top of the file.

Example
<?php
class User {
public function getName() {
return "John Doe";
}
}
namespace MyApp;
?>

Constants, classes and functions declared in this file will belong to the Html namespace:


Create a Table class in the Html namespace:

Example
<?php
namespace HTML;
class Table {
public function draw() {
return "<table></table>";
}
}
?>
Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.