PHP wishlist/trait implements: Difference between revisions

From Woozle Writes Code
Jump to navigation Jump to search
(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...")
 
(crosslink)
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
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 both independent of class-hierarchy, and it's kind of odd that this isn't being leveraged.
As long as <code>trait</code>s and <code>interface</code>s are different things (and [[../combine traits and interfaces|I don't really understand why they are]]), 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 both independent of class-hierarchy, and it's kind of odd that this isn't being leveraged.


Example to show syntax:
Example to show syntax:

Latest revision as of 22:49, 24 November 2021

As long as traits and interfaces are different things (and I don't really understand why they are), 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).