Traits का सबसे बड़ा फ़ायदा और सबसे बड़ी चुनौती (Conflict) समझने के लिए यह उदाहरण देखें

Traits का सबसे बड़ा फ़ायदा और सबसे बड़ी चुनौती (Conflict) समझने के लिए यह उदाहरण देखें

मान लीजिए हमारे पास दो Traits हैं और दोनों में share() नाम का एक जैसा फंक्शन है। जब हम इन्हें एक ही क्लास में इस्तेमाल करेंगे, तो हमें PHP को बताना होगा कि कौन सा फंक्शन चुनना है।

प्रैक्टिकल कोड उदाहरण (Conflict Resolution)

<?php

trait WhatsApp {
    public function share() {
        echo "Sharing content via WhatsApp \n";
    }
}

trait Telegram {
    public function share() {
        echo "Sharing content via Telegram \n";
    }
}

class Post {
    // यहाँ Conflict होगा क्योंकि दोनों Traits में share() मेथड है
    use WhatsApp, Telegram {
        // WhatsApp वाले share को Telegram वाले पर प्राथमिकता दें
        WhatsApp::share insteadof Telegram;
        
        // Telegram वाले share को एक नया नाम (Alias) दें ताकि उसे भी इस्तेमाल किया जा सके
        Telegram::share as shareOnTelegram;
    }
}

$myPost = new Post();

// यह WhatsApp वाला मेथड चलाएगा
$myPost->share(); 

// यह Telegram वाला मेथड चलाएगा (Alias के ज़रिए)
$myPost->shareOnTelegram(); 

?>

Output:

Sharing content via WhatsApp
Sharing content via Telegram 

Comments

Popular posts from this blog

How To Create Your Own Custom Widgets Wordpress

Experience about PHP, Laravel, Prestashop

Prestashop PDF Download Error