Web Development
28-05-2024

Using alias for Traits

Dmytro Tus
Full Stack Web developer

Let's look at this example of code

<?php

trait Helper{
    public function getName(){
        return 'TraitName';
    }
}


class MyClass{
    use Helper;

    public function getName(){
        return 'ClassName';
    }

    public function __construct()
    {
        echo $this->getName();
    }
}


new MyClass();

How do you think what should be output?

The correct answer is below:

///ClassName

That means, when we have traits, and the method has the same name, the priority is for class, later comes trait.

But what if we have the same function name inside trait and basic class and we need to use both.

The approach is very simple.

We can use aliases like this:

<?php

trait Helper{
    public function getName()
    {
        return 'TraitName';
    }
}


class MyClass{
    use Helper{
        Helper::getName as getTraitName;
    }

    public function getName(){
        return 'ClassName';
    }

    public function __construct()
    {
        echo $this->getName();
        echo $this->getTraitName();
    }
}


new MyClass();
////ClassNameTraitName

That's all, happy coding 🙂

 

 

 

Image from unsplash Ben Griffiths


Tags:

Another posts