In php traits have some feature like interface and abstract class has and traits also facilitate in inheritance.Any real world example or discussion relating Trait,Interface,Abstract class and Interface.
Let there be 2 classes : Mailer
and Writer
.
Mailer
sends some text by mail, where Writer
writes text in a file.
Now imagine you want to format the input text used by both classes.
Both classes will you use the same logic.
Mailer
and Writer
classes already extends some classes.So you use a trait
Example :
trait Formatter
{
public function format($data)
{
// Do some stuff
return $data;
}
}
class Mailer
{
use Formatter;
public function send($data)
{
$data = $this->format($data);
// Send your mail
}
}
class Writer
{
use Formatter;
public function write($data)
{
$data = $this->format($data);
// Write in file
}
}
In PHP, traits are like 'mini-classes'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With