← Back to PHP Course | Chapter 8: OOP | Lesson 9 of 14

PHP Traits

एक trait अलग-अलग classes को दिए जा सकने वाले skills के एक bundle जैसा है, जैसे swimming दोनों dog और duck को सिखाना। यह classes को related हुए बिना code share करने देता है।
Syntax
php
trait TraitName {
    function method_name() { }
}

class ClassName {
    use TraitName;   // mix the methods in
}

Traits क्या हैं?

एक trait methods का एक reusable block है जिसे use keyword इस्तेमाल करके कई, अन्यथा unrelated classes में mix किया जा सकता है, उन classes के बीच code share करने की problem solve करते हुए जो एक common parent share नहीं करतीं।

उदाहरण: What are Traits?

php
<?php
// Define the trait `Greetable`, reusable methods to mix into a class
trait Greetable {
    // Define the function `greet` with no parameters
    function greet() {
        // Print "Hello!" to the output
        echo "Hello!";
    }
}
// Define the class `User`
class User {
    // Import `Greetable` into this file
    use Greetable;
}
// Create a new `User` instance, stored in `$user`
$user = new User();
$user->greet();
?>

Traits Define और Use करना

Inheritance के उलट, एक trait is-a relationship establish नहीं करता — यह method implementations के एक set को copy करने का पूरी तरह mechanism है, इसलिए एक Loggable trait एक User class और एक Order class दोनों द्वारा इस्तेमाल हो सकता है बिना एक-दूसरे से किसी relation के।

उदाहरण: Defining and Using Traits

php
<?php
// Define the trait `Loggable`, reusable methods to mix into a class
trait Loggable {
    // Define the function `log` taking `$msg`
    function log($msg) {
        // Print "[LOG] $msg\n" to the output
        echo "[LOG] $msg\n";
    }
}
// Define the class `User`
class User {
    // Import `Loggable` into this file
    use Loggable;
}
// Define the class `Order`
class Order {
    // Import `Loggable` into this file
    use Loggable;
}
(new User())->log("User created");
(new Order())->log("Order placed");
?>

कई Traits

एक class एक साथ कई traits इस्तेमाल कर सकती है, और PHP के पास उन cases के लिए specific conflict-resolution rules (insteadof और as) हैं जहाँ इसके इस्तेमाल किए गए दो traits किसी same नाम वाले method को define कर देते हैं।

उदाहरण: Multiple Traits

php
<?php
// Define the trait `A`, reusable methods to mix into a class
trait A {
    // Define the function `hello` with no parameters
    function hello() { echo "A"; }
}
// Define the trait `B`, reusable methods to mix into a class
trait B {
    // Define the function `hello` with no parameters
    function hello() { echo "B"; }
}
// Define the class `MyClass`
class MyClass {
    use A, B {
        A::hello insteadof B;
    }
}
(new MyClass())->hello();
?>

Conflict Resolution (insteadof)

Traits abstract methods भी define कर सकते हैं, इन्हें इस्तेमाल करने वाली class को एक implementation supply करने की माँग करते हुए, जो एक trait को उस behavior पर depend करने देता है जिसकी उसे host class से उम्मीद है।

उदाहरण: Conflict Resolution (insteadof)

php
<?php
// Define the trait `Shape`, reusable methods to mix into a class
trait Shape {
    // Define the function `area` with no parameters
    abstract function area();
    // Define the function `describe` with no parameters
    function describe() {
        // Print `"Area: " . $this->area()` to the output
        echo "Area: " . $this->area();
    }
}
// Define the class `Square`
class Square {
    // Import `Shape` into this file
    use Shape;
    // Define the function `area` with no parameters
    function area() {
        // Return `16` from this function
        return 16;
    }
}
(new Square())->describe();
?>

Trait Methods की Visibility

Traits logging, timestamping, या serialization helpers जैसी cross-cutting concerns के लिए एक अच्छा fit हैं जिनकी कई अन्यथा-unrelated classes को ज़रूरत होती है, उन classes को एक artificial inheritance hierarchy में मजबूर किए बिना।

उदाहरण: Trait Methods Visibility

php
<?php
// Define the trait `Timestampable`, reusable methods to mix into a class
trait Timestampable {
    // Define the function `timestamp` with no parameters
    function timestamp() {
        // Return `date("Y-m-d")` from this function
        return date("Y-m-d");
    }
}
// Define the class `Post`
class Post {
    // Import `Timestampable` into this file
    use Timestampable;
}
// Define the class `Comment`
class Comment {
    // Import `Timestampable` into this file
    use Timestampable;
}
// Print `(new Post())->timestamp()` to the output
echo (new Post())->timestamp();
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. same method name वाले दो traits इस्तेमाल करना और conflict को insteadof से resolve न करना।
  2. किसी trait से सीधे एक object बनाने की कोशिश करना, जो possible नहीं है।
  3. यह उम्मीद करना कि traits inheritance जैसे काम करेंगे, जबकि वे सिर्फ अपना code class में copy करते हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.