LoginSignup
5
5

More than 5 years have passed since last update.

[PHP]抽象クラスとTraitのコードを見比べる。

Last updated at Posted at 2014-10-01

書き比べればなんとかなるはず

抽象クラス

abstract.php
<?php

abstract class Working
{
    abstract protected function where();
    abstract protected function why();
    abstract protected function how();

    public function work()
    {
        echo $this->where($where);
        echo $this->why($reason);
        echo $this->how($how);
    }
}

class Person extends Working
{
    protected function where()
    {
        return '横浜で';
    }

    protected function why()
    {
        return 'お金欲しいから';
    }

    protected function how()
    {
        return '営業する';
    }
}

$bob = new Person();
$bob->work(); // 横浜でお金欲しいから営業する

trait

traitの1文字目は小文字、のはず…
http://www.infiniteloop.co.jp/docs/psr/psr-2-coding-style-guide.html

trait.php
<?php

trait Working
{
    protected function where($where)
    {
        return $where;
    }

    protected function why($reason)
    {
        return $reason;
    }

    protected function how($how)
    {
        return $how;
    }

    public function work($where, $reason, $how)
    {
        echo $this->where($where);
        echo $this->why($reason);
        echo $this->how($how);
    }
}

class Person
{
    use Working;
}

$bob = new Person();
$where = '横浜で';
$why = 'お金欲しいから';
$reason = '営業する';
$bob->work($where, $why, $reason); // 横浜でお金欲しいから営業する

結果

ニャル子さんが言う通り、変更頻度が低い実装は、
traitに抜き出したほうが良さそう。
抽象クラスは多重継承した時に、やっかいなことになりそう。
そもそも多重継承ってなくした方がよさそう

5
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5