9
12

More than 5 years have passed since last update.

traitでabstract methodを使ってクラスの変数にアクセスする

Last updated at Posted at 2014-08-28

PHPのtrait。まだ使いこなせません。

例えばtraitでメンバー変数を扱うことが出来ます。

trait HelloTrait {
  protected $hello = 'hello trait';
  function hello() {
    echo $this->hello;
  }
}

ただ、この$helloのメンバー変数をクラスと共有しようとすると面倒です。

クラスで設定したメンバー変数の値を表示する場合です。

class Hello {
  use HelloTrait;
  protected $hello = 'hello class';
}
echo (new Hello)->hello();

上のコードはFatalエラーを発生します(するはず。実は走らせてない…)。クラスとtraitで同じメンバー変数がありますが、値が違うからです。同じにしてもE_STRICTエラーが発生します。

ならば、traitのprotected $helloを削除すればエラーがなくなりますが、traitで使っているメンバー変数が存在しないので、変です。それに$helloを持たないクラスで使うとエラーが出るかもしれません。

そんな時はgetter関数を使います。
例えばfunction getHello()

更にtrait内でabstractメソッドを指定してあげると使い勝手が上がります。

trait HelloTrait {
  abstract protected function getHello();
  function hello() {
    echo $this->getHello();
  }
}

class Hello {
  use HelloTrait;
  protected $hello = 'hello class';
  protected function getHello() {
    return $this->hello;
  }
}

クラス側でgetHelloメソッドを持たないクラスでHelloTraitを使うと、すぐエラーがでて問題が分かります。

値を変えるときは、同じようにsetterメソッドを追加します。

参考:http://www.slideshare.net/mikestowe/traits-and-horizonal-design

9
12
0

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
9
12