🔴 Advanced  ·  Lesson 21

Namespaces

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 User class without conflict.
  • They make large projects organized (used heavily by Composer/Laravel).

Summary

  • Namespaces group code and prevent name conflicts.
  • Define with namespace, import with use.

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 के User class हो सकती है।
  • बड़े projects organized रखते हैं (Composer/Laravel में बहुत use)।

सारांश

  • Namespaces code group करते हैं और name conflicts रोकते हैं।
  • namespace से define, use से import।
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।