Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traits in php- Any real world example

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.

like image 460
P.Akondo Avatar asked Nov 25 '16 11:11

P.Akondo


1 Answers

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.

  • You could create an interface, but you will need to duplicate the logic in both classes.
  • You could create a parent class and extend it, but PHP doesn't allow inheritance of multiple classes. This will become a problem if your 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'.

like image 76
Max Avatar answered Sep 28 '22 03:09

Max