5

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.

P.Akondo
  • 53
  • 7
  • Hi, did you understood ? – Max Nov 27 '16 at 09:48
  • 1
    Possible duplicate of [Traits in PHP – any real world examples/best practices?](http://stackoverflow.com/questions/7892749/traits-in-php-any-real-world-examples-best-practices) – sepehr Nov 27 '16 at 17:09

1 Answers1

7

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'.

Max
  • 891
  • 8
  • 17