🔴 Advanced  ·  Lesson 23

Traits

Traits

What is a Trait?

A trait lets you reuse a set of methods in multiple classes — solving PHP's "no multiple inheritance" limit. You include a trait with the use keyword.

Example

trait Logger {
    public function log($msg) {
        echo "LOG: $msg";
    }
}

class User {
    use Logger;
}

$u = new User();
$u->log("User created");  // LOG: User created

Trait vs Interface

TraitInterface
contains real method codeonly method names (no body)
for code reusefor a common contract

Summary

  • A trait shares real method code across classes via use.
  • Interface = contract (no code); trait = reusable code.

Trait क्या है?

Trait आपको methods का set कई classes में reuse करने देता है — PHP की "no multiple inheritance" सीमा हल करता है। Trait को use keyword से शामिल करते हैं।

Example

trait Logger {
    public function log($msg) {
        echo "LOG: $msg";
    }
}

class User {
    use Logger;
}

$u = new User();
$u->log("User created");  // LOG: User created

Trait बनाम Interface

TraitInterface
असली method code रखता हैसिर्फ method names (no body)
code reuse के लिएcommon contract के लिए

सारांश

  • Trait use से असली method code कई classes में share करता है।
  • Interface = contract (no code); trait = reusable code।
← Back to PHP Tutorial
🔗

Share this topic with a friend

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

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

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