Sign up for our free newsletter

Blog

PHP 5.4 – Traits

by on

The recent release of PHP 5.4 includes a new feature called Traits. It enables method injection into classes and the concept will be familiar to anyone who has experience with Ruby’s mixins or traits in Scala. CakePHP’s ‘Model Behaviour’ functionality is also influenced by the concept of traits and mixins.

Traits are similar to abstract classes, however they are particularly useful when a method has applications across a wide area of concerns. They can be used to avoid generic abstract classes and interfaces that are often used to compensate for PHP’s lack of multiple inheritance.

In its simplest form, a trait can have no interaction with the class it is injected into:

<?php 
trait HelloWorld 
{
	public function helloWorld()
	{
		echo "Hello World";
	}
}

class Person 
{
	use HelloWorld;
}

$person = new Person();
$person->helloWorld();
?>

However its real power lies in retrieving and/or manipulating object properties – especially when the function could be applied to classes that have no direct similarities:

<?php

trait ClassDetails
{
	public function getClassDetails()
	{
		$className = get_class($this);
		$output = "Class name: $className. ";

		$parentClassName = get_parent_class($this);
		if($parentClassName === false) {
			$output .= "No parent class";
		} else {
			$output .= "Parent class name: $parentClassName.";
		}

		return $output;
	}
}

class Person 
{
	use ClassDetails;
}

$person = new Person();
echo $person->getClassDetails(); /* returns 'Class name: Person. No parent class.' */

class MysqlConnection extends DbConnection
{
	use ClassDetails;
}

$connection = new MysqlConnection();
echo $connection->getClassDetails(); /* returns 'Class name: MysqlConnection. Parent class name: DbConnection.' */

?>

For further details on traits in PHP 5.4, see http://php.net/traits.

About the author

Hi I'm Peter, currently I work as the Platform Engineer for Wooboard. I have also worked on Friendorse. Since joining Pollenizer I have learnt [...]

More posts by Peter Anderson

Share

Back to posts

Singapore Startup FAQ

by: Isaac Souweine

I've met with dozens of folks over the past months who are interested in the Singapore startup scene [...]

Thanks for the time at the Hive (Guest Post)

by: Phil Morle

This is a quest post from Holly Cardew, one of the founders of Pixc. It's been a great example of how startups can benefit from co-working at Pollenizer.  Eight weeks ago I [...]