Traits in PHP 5.4 – Why we need Traits

This entry is part 3 of 5 in the series New in PHP 5.4

Traits is one major addition to PHP. We read an introductory article about Traits in PHP 5.4. In the post, we saw an example code which only resembles single inheritance. So, what is the actual purpose of Traits and why do we need to use Traits in our code.

Suppose a website has two types of clients; Business and Individual. Both entities will have certain address associated to them. This will require writing accessor and mutator methods for address in the classes of both entities. However, using the OOPS approach, we can create a new Client class and define those accessor and mutator methods in it. Both Individual and Business will inherit Client class. So, the Individual and Business classes will inherit the address getter and setter methods from Client class. But, Business and Individual are not the only entities that have an address.

// Class Client

class Client

{

private $address;

public function getAddress() {

return $this->address;

}

public function setAddress($address) {

$this->address = $address;

}

}

// Class Business

class Business extends Client

{

// Can use getAddress() and setAddress() methods in client class.

}

// Class Individual

class Individual extends Client

{

// Can use getAddress() and setAddress() methods in client class.

}

There can be another entity Order that can have shipping and billing addresses. Now, Order cannot inherit Client. So, although, creating Client class solved the problem to some extent; it is not eliminated. Trait is the solution here.

You can define the accessor and mutator methods in the traits and use the address trait wherever you intend to use getAddress() and setAddress() methods (These are accessor and mutator methods for property “address”).

// Trait Address

trait Address

{

private $address;

public function getAddress() {

return $this->address;

}

public function setAddress($address) {

$this->address = $address;

}

}

// Class Business

class Business

{

use Address;

// Can use getAddress() and setAddress() methods in client class.

}

// Class Individual

class Individual

{

use Address;

// Can use getAddress() and setAddress() methods in client class.

}

// Class Order

class Order

{

use Address;

// Can use getAddress() and setAddress() methods in client class.

} 

Traits is a major new addition to PHP and we will cover this as a set of three posts within the New in PHP series.

Series Navigation<< Traits in PHP 5.4 – IntroductionPHP 5.4 – built-in web-server, closures, callable and other new features >>

5 Responses to “Traits in PHP 5.4 – Why we need Traits”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>