I wonder if my php interpreter doesn't work correctly or if I'm understanding Traits wrong. Here's my piece of code:
<?php
trait ExampleTrait{
public function foo()
{
echo 'y';
}
}
class ExampleClass
{
use ExampleTrait;
public function foo()
{
echo 'x';
}
}
$exCl = new ExampleClass();
$exCl->foo();
I assume this should show "y", but it shows "x" instead. Why?
Read this carefully Trait documentation I recommend to try out every example and make your own modifications to be sure you understand it. There is my example, hope it helps:
<?php
class A {
public function foo() {
echo "x";
}
}
class B extends A {}
$test = new B();
$test->foo();
// result X
This is pretty clear I think, so now lets use a Trait:
<?php
class A {
public function foo() {
echo "x";
}
}
trait T {
public function foo() {
echo "y";
}
}
class B extends A {
use T;
}
$test = new B();
$test->foo();
// result y
As you can see the Trait method overwrites the base class method. And now lets create a foo method in the B class
<?php
class A {
public function foo() {
echo "x";
}
}
trait T {
public function foo() {
echo "y";
}
}
class B extends A {
use T;
public function foo() {
echo "z";
}
}
$test = new B();
$test->foo();
// result z
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.
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