traits vs inheritance is that me

2017-03-24  本文已影响0人  张霸天

Another difference with traits vs inheritance is that methods defined in traits can access methods and properties of the class they're used in, including private ones.

For example:
<?php
trait MyTrait
{
  protected function accessVar()
  {
    return $this->var;
  }

}

class TraitUser
{
  use MyTrait;

  private $var = 'var';

  public function getVar()
  {
    return $this->accessVar();
  }
}

$t = new TraitUser();
echo $t->getVar(); // -> 'var'                                                                                                                                                                                                                          

?>
上一篇下一篇

猜你喜欢

热点阅读