PHP wishlist/trait implements

From Woozle Writes Code
< PHP wishlist
Revision as of 14:28, 19 August 2021 by Woozle (talk | contribs) (Created page with "Traits should be able to <code>implement</code> one or more interfaces, the way classes can. Traits and interfaces are kind of a perfect match for each other, since they're bo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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).