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'
?>
网友评论