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)