RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

Method with same name called from Interface not from Trait?

I have created same method printData() in the MyInterface.php and MyTrait.php and i am calling the method printData() from my controller which implements the MyInterface.php and use MyTrait.php. But the method is always calling from MyInterface.php. Please explain it why this occurs?

MyInterface.php

<?php namespace App\Interfaces;

interface MyInterface
{
    public function printData();
}

MyTrait.php

<?php namespace App\Traits;

trait MyTrait
{
    public function printData()
    {
        dd("From Trait");
    }
}

HomeController.php

<?php namespace App\Http\Controllers;

use App\Interfaces\MyInterface;
use App\Traits\MyTrait;
use App\User;

class HomeController extends Controller implements MyInterface
{
    use MyTrait;

    public function index()
    {
        $this->printData();
    }

    public function printData() {
        // TODO: Implement printData() method.
        dd("From Interface");
    }
}

Upvotes: 1

Views: 946

Answers (2)

mega6382
mega6382

Reputation: 9396

Try using it like this:

class HomeController extends Controller implements MyInterface
{
    use MyTrait{
        printData as MyTraitPrintData;
    }

    public function index()
    {
        $this->MyTraitPrintData();
    }

    public function printData()
    {

        dd("From Interface");
    }
}

Traits are meant to provide reusable methods and properties. They will not override the class's own methods. By defining printData() inside the HomeController you are actually overriding the printData() inside MyTrait. That is why you have to differentiate them from each other.

Learn more about all this in Horizontal Reuse for PHP

Upvotes: 6

Lloople
Lloople

Reputation: 1844

The method is not calling from MyInterface but from HomeController.

The reason is because HomeController acquires the method from the trait MyTrait but then overrides it.

If you want that method in your trait, you don't need to declare an interface.

What interfaces do is forcing the classes which implements it to declare those methods, but you don't want to do that since you're creating the method in a Trait..

Upvotes: 1

Related Questions