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

How many types of inheritances used in php and how we achieve it.

0 Answers  


How to return ascii value of character in php?

0 Answers  


Explain about Functions in PHP?

1 Answers  


What is csrf token in php?

0 Answers  


sort term descripttion form, report and uery

0 Answers  






What is the purpose of basename() function in PHP?

0 Answers  


What is difference between static and constant in php?

0 Answers  


what method is used to generate a random number?

4 Answers  


Can we extend two classes in php?

0 Answers  


What are the different opening and closing tags available in PHP?

0 Answers  


What does the arrow mean in php?

0 Answers  


How do you find the length of a string in php?

0 Answers  


Categories