I\'m wondering why PHP Trait (PHP 5.4) cannot implement interfaces.
Update from user1460043\'s answer => ...cannot require class which uses it to implement a
I agree with the response of @Danack, however I will complement it a little.
The really short version is simpler because you can't. That's not how Traits work.
I can only think of few cases in which what you request is necessary and is more evident as a design problem than as a language failure. Just imagine that there is an interface like this:
interface Weaponize
{
public function hasAmmunition();
public function pullTrigger();
public function fire();
public function recharge();
}
A trait has been created that implements one of the functions defined in the interface but in the process uses other functions also defined by the interface, prone to the error that if the class that uses the feature does not implement the interface everything fails to pull the trigger
trait Triggerable
{
public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}
class Warrior
{
use Triggerable;
}
An easy solution is simply to force the class that uses the trait to implement those functions as well:
trait Triggerable
{
public abstract function hasAmmunition();
public abstract function fire();
public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}
So the trait isn't completely dependent on the interface, but a proposal to implement one of its functions, since when using the trait the class will demand the implementation of the abstract methods.
interface Weaponize
{
public function hasAmmunition();
public function pullTrigger();
public function fire();
public function recharge();
}
trait Triggerable
{
public abstract function hasAmmunition();
public abstract function fire();
public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}
class Warrior implements Weaponize
{
use Triggerable;
public function hasAmmunition()
{
// TODO: Implement hasAmmunition() method.
}
public function fire()
{
// TODO: Implement fire() method.
}
public function recharge()
{
// TODO: Implement recharge() method.
}
}
Please excuse my English