PHP wishlist/trait implements: Difference between revisions
m (Woozle moved page PHP wishlist/implementation traits to PHP wishlist/trait implements without leaving a redirect: better name) |
(crosslink) |
||
Line 1: | Line 1: | ||
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 trait
s and interface
s 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).