PHP: dealing with traits with methods of same name
Asked Answered
H

2

13

I've search all over this site and google and I ended up creating this account...
I need some help with php, traits and classes. I have this 2 different traits, that have some methods with the same name.

The problem relies on that I need both of them! I can't use insteadof...

Here goes an example code: http://sandbox.onlinephpfunctions.com/code/b69f8e73cccd2dfd16f9d24c5d8502b21083c1a3

trait traitA {
    protected $myvar;
    public function myfunc($a) { $this->myvar = $a; }
}

trait traitB
{
    public function myfunc($a) { $this->myvar = $a * $a; }
}


class myclass 
{
    protected $othervar;

    use traitA, traitB {
        traitA::myfunc as protected t1_myfunc;
        traitB::myfunc as protected t2_myfunc;
    }

    public function func($a) {
        $this->myvar = $a * 10;
        $this->othervar = t2_myfunc($a);
    }

    public function get() { 
        echo "myvar: " . $this->myvar . " - othervar: " . $this->othervar; 
    }
}

$o = new myclass;
$o->func(2);
$o->get();

So, this example ends in an obvious

Fatal error: Trait method myfunc has not been applied, because there are collisions with other trait methods on myclass

How can I solve this without changing those method's name? Is it possible?

On a side note, this is the worst editor I've ever seen in my life!

Heddie answered 11/5, 2014 at 17:23 Comment(0)
A
12

You still need to resolve the conflict in favour of one trait. Here you only aliased the name. It's not a renaming, but an alias.

Add to the use block:

traitA::myfunc insteadof traitB;

(or traitB::myfunc insteadof traitA;)

and it should work.

You now have two aliases as wanted and the conflict is resolved too.

Amalgamation answered 11/5, 2014 at 17:32 Comment(2)
Excelent! I had a typo there in $this->othervar = $this-> t2_myfunc($a) xD Your solution works, can't believe it was so easy :SHeddie
A full example including the question's code would be helpful.Ulberto
A
0

You can do like this :

use traitA, traitB {
    traitA::myFunc insteadof traitB; //uses traitA myFunc() method
    traitB::myFunc as myFuncB;       //alias traitB's myFunc method
}

In this way you can use functions from both trait.

Adp answered 22/7 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.