How to use Traits in PHP

How to use Traits in PHP

The traits is very important concept that help the developer to implement the reuse and optimization of the code . Before giving the exact defination of trais let me share advantage traits

  • The php provide only single inheritance but with the help of traits we can use coomon functions in class without need of inherritance.
  • The traits also help to optimized the code because we do not need to write same code in multiple file.
  • We can also reuse the code

The PHP documentation defines traits as
"Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins."

Now let explain how to implements this concept

trait Contact {
	
	function getContact()
	{
	  echo '<br> Contact Detail';
	  echo '<br> Phone : 604-1111-0000';
          echo '<br> Email : test123@gmail.com';
          echo '<br> East Hastings Street, Vancouver, BC';	  
		
	}
	
	
}

class College 
{
  const NAME = 'ABC Engineering College';	
	
}

class Employee extends College {
	use Contact;
	
}

class Student extends College {
	use Contact;
	
}

$objEmp = new Employee();
$objStud = new Student();
$objEmp->getContact();
echo '<hr>';
$objStud-> getContact();

Conflict Resolution and Aliasing

trait Student {
	
	function getContact()
	{
	  echo '<br> Contact Detail For Student';
	  echo '<br> Phone : 604-1111-0000';
          echo '<br> Email : student123@gmail.com';
          echo '<br> East Hastings Street, Vancouver, BC';	  
		
	}
	
	
}

trait Employee {
	
	function getContact()
	{
	  echo '<br> Contact Detail For Employee';
	  echo '<br> Phone : 604-1111-9999';
          echo '<br> Email : employee123@gmail.com';
          echo '<br> burrard Street, Vancouver, BC';	  
		
	}
	
	
}

class College 
{
  use Student, Employee {
        Student::getContact as getContactForStudent;
        Employee::getContact insteadof Student;
    }
	
}

$objCollege = new College();
$objCollege->getContactForStudent();
echo '<hr>';
$objCollege->getContact();

Tags