What are traits? How is it used in php?



What are traits? How is it used in php?..

Answer / zahid

In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies.

Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword

Example:

trait hello {
public function message1() {
echo "Nature is precious,
";
}
}

trait world{
public function message2() {
echo "So Let us unite to preserve it";
}
}

class InUnity {
use hello;
}

class WeCan {
use hello, world;
}

$obj = new InUnity();
$obj->message1();
echo "****************
";
$obj2 = new WeCan();
$obj2->message1();
$obj2->message2();

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More PHP Interview Questions

Explain what does the expression exception::__tostring means?

0 Answers  


how we can crop an image and how we can display it..

1 Answers   Satyam,


How do I check environment variables?

0 Answers  


What is php data type?

0 Answers  


What are the differences between require and include?

0 Answers  


What are the uses of php language?

0 Answers  


Tell me what should we do to be able to export data into an excel file?

0 Answers  


Which is the correct way to check if a session has already been started ?

0 Answers  


Which is useful for method overloading?

0 Answers  


What are different types of runtime errors in php?

0 Answers  


What is the role of the .htaccess file in php?

0 Answers  


Is time a dependent variable?

0 Answers  


Categories