🔴 Advanced · Lesson 21
Namespaces
What is a Namespace?
A namespace groups related classes/functions and prevents name clashes when two libraries have a class with the same name.
Defining and Using
// File: app/Models/User.php
namespace App\Models;
class User {
public function hello() { return "App User"; }
}
// Another file - use it
use App\Models\User;
$u = new User();
echo $u->hello(); // App User
Why Namespaces?
- Two libraries can both have a
Userclass without conflict. - They make large projects organized (used heavily by Composer/Laravel).
Summary
- Namespaces group code and prevent name conflicts.
- Define with
namespace, import withuse.
Namespace क्या है?
Namespace related classes/functions को group करता है और name clashes रोकता है जब दो libraries में एक ही नाम की class हो।
Define और Use करना
// File: app/Models/User.php
namespace App\Models;
class User {
public function hello() { return "App User"; }
}
// दूसरी file - use करें
use App\Models\User;
$u = new User();
echo $u->hello(); // App User
Namespaces क्यों?
- दो libraries में बिना conflict के
Userclass हो सकती है। - बड़े projects organized रखते हैं (Composer/Laravel में बहुत use)।
सारांश
- Namespaces code group करते हैं और name conflicts रोकते हैं।
namespaceसे define,useसे import।
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.