Traits in PHP

Basically multiple inheritance does not supported by PHP. One class can only extend or inherit from one other class. But there are many cases when you want to extend more than one classes for code reusability. To overcome this problem, as of version 5.4, PHP introduced a new feature of code reuse named trait.

So what are Traits?. Traits are a mechanism for code reuse. A Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, but It is not allowed to instantiate a trait on its own.

/* mobile.php */

<?php

class Mobile{

	function model(){

		echo "Samsung Galexy 5 <br/>";
	}

}


/* charger.php */

<?php

trait Charger{

	function battery(){

		echo "2500 MP Battery <br/>";
	}

	function power(){

		echo "Power of Battery </br>";
	}


}


/* projector.php */

<?php

trait Projector{

	function range(){

		echo "Projector range 5 meter <br>";
	}

	function power(){

		echo "Power of range <br/>";
	}

	
}



/* body.php */

<?php

trait Body{

	function display(){

		echo "Display 5.5 inc <br/>";
	}

	public $name = "Smart Phone";

	abstract function tabu();
}


/* glass.php */

<?php

include_once('body.php');

trait Glass{

	use Body;

	/*function display(){

		echo "Cornic Gorila Glass <br>";
	}*/
}


/* index.php */

<?php

include_once('mobile.php');
include_once('charger.php');
include_once('projector.php');
include_once('glass.php');


class Samsung extends Mobile{

	use Charger,Projector,Glass{

		Charger::power insteadof Projector;
		Projector::power as Ppower;
	}

	/*function display(){

		echo "This is from index";
	}*/

	function tabu(){

	}
}



$obj = new Samsung;
$obj->model();
$obj->battery();
$obj->range();
$obj->power();
$obj->Ppower();
$obj->display();
echo $obj->name;


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s