Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Traits vs Interfaces

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 791
    Comment on it

    Welcome to Findnerd. Today we are going to discuss the difference between interface and traits. Interface is a contruct between program and programmer. You can say like this, it is blueprint for the classes. Interface has abstact methods which must be implemented in implementing class. You can simply add the interface with the help of implements keyword to the class. Please have a look.

    <?php
    interface Data
    {
    public function getData(Data $data);
    public function setData();
    }
    Class Student implements Data
    {
    protected $data;
    public function setData(Data $data){
    $this->data = $data;
    }
    public function getData(){
    return $this->data;
    }
    }
    
    ?> 
    

    In above example, we have to implement both the methods of interface data. If we create a new other class that is Teacher then we have to redefinite these methods again. Here we have to write the same code again. To aviod this, we can use the traits. Please have a look.

    <?php
    trait Data
    {
    protected $data;
     public function setData(Data $data){
    $this->data = $data;
    }
    public function getData(){
    return $this->data;
    }
    }
    class Student 
    {
    use Data;
    }
    class Teacher
    {
    use Data;
    }
    ?>
    

    In above example we created a trait with name Data and also created Student,Teacher classes. We are using trait in these classes.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: