I have got a trait
trait Foo{
protected static function foo(){
echo 'Hello';
}
}
and a class
class Bar{
use Foo;
private static function foo(){
Foo::foo();
echo ' World!';
}
}
I cannot use Foo:foo()
. What can I do to achieve the desired effect?
EDIT
Using
use Foo {foo as parentFoo}
private static function foo(){
self::parentFoo();
echo ' World!';
}
did the trick.
In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.
Overriding a trait function Let's create a simple trait and use it in a class. Executing (new MyClass)->sayHi(); will output "trait says hi". The trait function can be overridden simply by defining a function with the same name in the class. Now (new MyClass)->sayHi(); will output "class says hi".
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
Only classes can be extended. Traits are not classes.
You can do something like this:
class Bar{
use Foo {
Foo::foo as foofoo;
}
private static function foo(){
self::foofoo();
echo ' World!';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With