Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why trait does not override method in class?

Tags:

php

traits

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?

like image 908
drakonli Avatar asked Jan 08 '23 22:01

drakonli


1 Answers

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.

like image 113
Zoltán Jére Avatar answered Jan 18 '23 13:01

Zoltán Jére