Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: dealing with traits with methods of same name

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!

like image 943
HacKan Avatar asked May 11 '14 17:05

HacKan


People also ask

Can traits have abstract methods PHP?

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).

Can traits use traits PHP?

Traits ¶ PHP implements a way to reuse code called Traits. Traits are a mechanism for code reuse in single inheritance languages such as PHP.

How do you name a trait in PHP?

Naming conventions for code released by PHP FIG¶ Interfaces MUST be suffixed by Interface : e.g. Psr\Foo\BarInterface . Abstract classes MUST be prefixed by Abstract : e.g. Psr\Foo\AbstractBar . Traits MUST be suffixed by Trait : e.g. Psr\Foo\BarTrait . PSR-1, 4, and 12 MUST be followed.

Can PHP traits have constructors?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.


1 Answers

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.

like image 121
bwoebi Avatar answered Oct 21 '22 10:10

bwoebi