PHP/trait/use
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. There unfortunately does not seem to be a page specifically documenting its syntax; most (but not all) of the applicable syntax can be found on the traits documentation page.
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
This is currently not documented on the traits page; I'm not sure where I found it.
Starting again with fresh example code, here is the problem:
trait tSample1 {
function Func1() {}
}
trait tSample2 {
use tSample1;
function Func1() {
parent::Func1(); // This doesn't work! A "use"d trait is not a parent.
}
}
To fix this, alter tSample2 thusly:
trait tSample2 {
use tSample1 { tSample1::Func1 as parent_Func1; }
function Func1() {
parent_Func1(); // We'll pretend we're a real family. (Are you my mummy?)
}
}
In case you need to alias multiple functions (starting over):
// 2022-04-13 I reconstructed this syntax through trial-and-error, but I swear it's in the docs. Somewhere.
trait tSample1 {
function Func1() {}
function Func2() {}
function Func3() {}
}
trait tSample2 {
use tSample1 {
tSample1::Func1 as parent_Func1;
tSample1::Func2 as parent_Func2;
tSample1::Func3 as parent_Func3;
}
function Func1() { $this->parent_Func1(); }
function Func2() { $this->parent_Func2(); }
function Func3() { $this->parent_Func3(); }
}
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.
Errors
Required Trait wasn't added
Fatal error: Required Trait <trait name> wasn't added to <class or trait name> in <filename> on line <line #>
This may result from aliasing methods from multiple traits but not including all of them in the "use" statement.
- Example:
use A { A::F1 as parent_F1; B::F2 as parent_F2; }
should beuse A,B {...