What are traits? How is it used in php?

Answer Posted / 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       View All Answers


Please Help Members By Posting Answers For Below Questions

How to remove duplicate values from a PHP Array?

547


What is a trait in php?

574


What is cookie and session in php?

513


Is nan in php?

531


How do you measure variables?

524






Which is incorrect with respect to separating php code and html?

540


Which function is used in php to check the data type of any variable?

518


What is a stored procedure in mysql?

531


What is the basic function to search files for lines (or other units of text) that contain a pattern.

574


What does sign mean php?

561


Explain the ternary conditional operator in php?

602


Explain what are the different errors in php?

555


How to remove white spaces from the beginning and/or the end of a string in php?

544


What does $_env mean?

573


Write a select query that will be displayed the duplicated site name and how many times it is duplicated?

573