PHP wishlist/trait implements

From Woozle Writes Code
< PHP wishlist
Revision as of 14:29, 19 August 2021 by Woozle (talk | contribs) (Woozle moved page PHP wishlist/implementation traits to PHP wishlist/trait implements without leaving a redirect: better name)
Jump to navigation Jump to search

Traits should be able to implement one or more interfaces, the way classes can. Traits and interfaces are kind of a perfect match for each other, since they're both independent of class-hierarchy, and it's kind of odd that this isn't being leveraged.

Example to show syntax:

interface ifAnimal {
    function MakeNoise();
}

trait tDog implements ifAnimal {
    public function MakeNoise() { $this->Woof(); }
    protected function Woof() { ... }
}

class cAlsatian {
   use tDog;
}

The cAlsatian class then doesn't also have to be declared with implements ifAnimal in order for a cAlsatian object to be used where ifAnimal is required.

More useful example:

interface ifAnimal {
    function MakeNoise();
}

trait tStandardAnimal implements ifAnimal {
    public function MakeNoise() { $this->PlaySample($this->NoiseFile()); }
    abstract protected function NoiseFile() : string; // filename containing noise for this animal
    protected function PlaySample(string $sFileName) { /* ... */ }
}

class cDog {
    use tStandardAnimal; // forces non-abstract cDog classes to define NoiseFile() and declares that their objects satisfy ifAnimal
// ...
}

This shows tStandardAnimal being used as a trait/interface hybrid: it declares that cDog will conform to ifAnimal while also being a little more specific about how ifAnimal's functionality is implemented (it plays an audio file, and implementers need to define the function which provides the name of that file).