【PHP】トレイト

<?php 

trait Dumper
{
    public function dump(string $msg)
    {
        $className = __CLASS__;
        echo date("Y-m-d h:i:s", time()).": [{$className}] {$msg}\n";
    }
}

class Book
{
    use Dumper;

    public $title;

    function __construct(string $title)
    {
        $this->title = $title;
        $this->dump("Created '{$this->title}'"); // Dumperトレイトで定義されたメソッド
    }

    public function getTitle()
    {
        return $this->title;
    }
}

class Bookshelf
{
    use Dumper;

    public function add(Book $book)
    {
        $this->books[] = $book;
        $this->dump("Added book '{$book->getTitle()}'"); // Dumperトレイトで定義されたメソッド
    }
}

$bookshelf = new Bookshelf();
$bookshelf->add(new Book('The Very Hungry Caterpillar'));

// 2018-04-17 01:21:09: [Book] Created 'The Very Hungry Caterpillar'
// 2018-04-17 01:21:09: [Bookshelf] Added book 'The Very Hungry Caterpillar'