1.

What Is Traits In Php?

Answer»
  • Traits are a mechanism for code reuse in single inheritance.
  • A TRAIT is similar to a class, but only intended to group functionality in a fine-grained and consistent way. 
  • It is not possible to instantiate a Trait but addition to traditional inheritance. It is intended to reduce some limitations of single inheritance to reuse sets of METHODS freely in SEVERAL independent classes living in different class hierarchies.
  • Multiple Traits can be INSERTED into a class by listing them in the use statement, separated by commas(,).
  • If two Traits insert a METHOD with the same name, a fatal error is produced.

Example of Traits:

class BaseClass{

function getReturnType() {

return 'BaseClass';

}

}

trait traitSample {

function getReturnType() {

echo "TraitSample:";

parent::getReturnType();

}

}

class Class1 extends BaseClass {

use traitSample;

}

$obj1 = new Class1();

$obj1->getReturnType();//TraitSample:BaseClass

Example of Traits:

class BaseClass{

function getReturnType() {

return 'BaseClass';

}

}

trait traitSample {

function getReturnType() {

echo "TraitSample:";

parent::getReturnType();

}

}

class Class1 extends BaseClass {

use traitSample;

}

$obj1 = new Class1();

$obj1->getReturnType();//TraitSample:BaseClass



Discussion

No Comment Found