Re: Traits with interfaces

From: Date: Thu, 01 Mar 2018 23:04:18 +0000
Subject: Re: Traits with interfaces
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-101949@lists.php.net to get a copy of this message
Hi all, On 01/03/2018 00:34, Marco Pivetta wrote:
- trait defined API can be imported with changed/aliased names, breaking therefore the contact defined in the interface
This isn't actually true, because trait method aliases create an *extra* copy of the pasted method, rather than actually renaming it. See example at the end of this e-mail for a demonstration. I'm not sure why this is; the original traits RFC [https://wiki.php.net/rfc/horizontalreuse#renaming] says that it is because of "the dynamic nature of PHP", but the example it gives doesn't actually show anything breaking. What *can* break an interface's contract is changing the *visibility* of the pasted method using "as protected" or "as private". This would need to be captured somehow while composing the class, probably producing a compile-time error, just as an explicit "implements" declaration would. While looking for the above RFC, I came across this draft by Kevin Gessner from 2 years ago for exactly the feature discussed here: https://wiki.php.net/rfc/traits-with-interfaces It includes references to potential uses of this feature, and equivalents in other languages. This appears to be the discussion in the archives, to avoid us repeating ourselves: https://marc.info/?t=145571923500003&r=1&w=2 and https://marc.info/?t=145573610000001&r=1&w=2 Appendix: Example of a trait providing implementation for an interface, even though the method was aliased: # https://3v4l.org/DMAoY interface Bobbable {
    public function bob();
} trait Bobber {
    public function bob() {
        echo "Bobbity";
    }
} class Bibble implements Bobbable {
    use Bobber { bob as bib; }
} $b = new Bibble; $b->bob(); $b->bib(); Regards, -- Rowan Collins [IMSoP]

« previous php.internals (#101949) next »