PHP/trait/use

from HTYP, the free directory anyone can edit if they can prove to me that they're not a spambot
< PHP‎ | trait
Revision as of 22:45, 13 April 2022 by Woozle (talk | contribs) (Created page with "==About== ''This sense of the '''use''' keyword is for including traits; there's another sense that only relates to namespaces.'' The '''use''' keyword allows a trait...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

About

This sense of the use keyword is for including traits; there's another sense that only relates to namespaces.

The use keyword allows a trait to be used within a class or another trait.

Basic Form

trait tSample1 {}
class cSample1 { use tSample1; }
trait tSample2 { use tSample1; }

Form for Multiple Traits

Building on the above example:

class cSample2 { use tSample1, tSample2; }
// This ^ is equivalent to:
class cSample2 {
    use tSample1;
    use tSample2;
}

Form for Conflict Resolution

Starting afresh...

trait tSample1 {
    function Func1() {}
    function Func2() {}
}
trait tSample2 {
    function Func1() {}
    function Func2() {}
}
// If we want to use both tSample3 and tSample4, how do we indicate which version of Func1() to use?
// Here's the syntax for that:
class cSample1 {
    use tSample1, tSample2 {
        tSample2::Func1 insteadof tSample1;
        tSample1::Func2 insteadof tSample2;
    }
}

Form for Pseudoparent Calls

I know this exists, but I'm still looking for the docs.

Other

You can also change the visibility (public/protected/private) of a function with "use", but I've never had occasion to... use... this feature.