Wednesday 16 April 2014

PHP 5.4 traits tutorial,example and concept


As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
PHP 5.4 introduces the concept of traits. Until Traits PHP uses Classical inheritance model in which one class can inherit only one class. In simple words Before PHP 5.4 PHP uses single inheritance model , which makes sometimes difficult to reuse the code.

Traits allow developer to reuse sets of methods freely in several independent classes living in different class hierarchies.



Lets first see what happens if you inherit two classes. For demostration purpose i create two classes one and two.
class one{

    public function printFirst(){

  echo "class one";
 }
}
class two{

  public function printSecond(){

  echo "class two";
 }
}
Extend class one two.
class some extends one two 
{

   public function printValues()
   {
        echo "hi there";
   }

}

 $demo = new Some;

 echo $demo->printValues();
 echo $demo->printFirst();
When you execute this code, it will give following error.
PHP Parse error:  syntax error, unexpected 'two' (T_STRING), expecting '{' i    n /var/www/srinu/traits.php on line ..
Now let’s check what happens, if we use traits.
For using trait in a class, use use keyword and trait name.
**In PHP we can use more than one trait in a class.
// Define trait one
trait one{

    public function printFirst(){
                echo "first";
        }   
}

// Define trait two

trait two{

        public function printSecond(){
                echo "second";
        }   

}

class some 
{
   use one,two;  // Calling traits

   public function printValues()
   {
        echo "hi there";
   }

}

   $demo = new Some;
   echo $demo->printFirst();
   echo $demo->printSecond();


Now this time we didn’t get any error, it executed perfectly and printed the desired result.

No comments:

Post a Comment