What is Traits and How it is used?

Traits are one of the biggest addition in the PHP 5.4.

In PHP trait is the method of code re-usability.As we know PHP is single inheritance programming language.As per my opinion, the main intention of introducing the trait in PHP is to reduce limitation of code re-usability in PHP single inheritance nature.  The structure of PHP traits is almost matched with a PHP class but here we group the re-usable methods. In traits, we can group methods which we need to re-declare in various class.Or if you have some different class which has the same function( the need features of the function is also same), then you can group those function and create PHP traits for that.

Let’s see some example

Here I declared one function on each trait and also on class and use all 4 traits on the class Me by use keyword.

<?php 
/* It supported multiple inheritence*/ 
trait age{ 
public function displayAge(){ 
echo "25"; 
} 
} 
trait gender{ 
public function displayGender(){ 
echo "male";
 }
 } 
trait bloodgroup{ 
public function displayBloodGroup(){ 
echo "B+"; 
}
 }
class Me{ 
use age,gender,bloodgroup; 
public function displayName(){ 
echo "Rupam"; 
} 
} 
$objme = new Me(); 
$objme->displayName(); // Rupam
$objme->displayAge(); // 25
$objme->displayGender(); // male
$objme->displayBloodGroup(); // B+

In this example, Talker uses the traits A and B. Since A and B have same methods but trait give a authority to define which function use for which trait by keyword insteadof.

trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

$objtalk = new Talker();
echo $objtalk->smallTalk(); //b
echo $objtalk->bigTalk(); // A

Using the as syntax, one can also adjust the visibility of the method in the exhibiting class.

trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

// Change visibility of sayHello
class MyClass1 {
    use HelloWorld { sayHello as protected; }
}

// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
    use HelloWorld { sayHello as myPrivateHello; }
}

$objmyclass = new MyClass2();
$objmyclass->myPrivateHello();
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *