happy cat image

everdevel

coding

login
NotificationX
  • Currently, only notices of comments are displayed.
  • no comment or please login

Determine the name to use instead of the trait's methods

If you have two traits and two traits have a method with the same name, you can specify which one to use.
The keyword insteadof to specify which method to use.

How To Use insteadof

trait trait name{}
class class name
{
    use trait name, trait name {
        The name of the trait to use :: method name insteadof the name of the trait to disable;
    }
}

So let's look at an example..

<?php
    trait apple
    {
        public function phone()
        {
            return 'iPhone';
        }
    }

    trait samsung
    {
        public function phone()
        {
            return 'galaxy';
        }
    }

    class disneyAnimation
    {
        use apple, samsung {
            apple::phone insteadof samsung;
        }
    }

    $disney = new disneyAnimation;
    echo "Judith in zootopia ".$disney->phone()." Use it." ;
?>

If you have 3 traits, instead of, write the name of the trait you don't want to use.

insteadof multiple usage

trait trait name{}
class class name
{
    use trait name, trait name {
        Use trade name ::method name insteadof not be used trade name, not be used trade name;
    }
}

Try insteadof in multiples with the following example:

<?php
    trait apple
    {
        public function phone()
        {
            return 'iPhone';
        }
    }

    trait samsung
    {
        public function phone()
        {
            return 'galaxy';
        }
    }

    trait lg
    {
        public function phone()
        {
            return 'g';
        }
    }

    class disneyAnimation
    {
        use apple, samsung, lg {
            apple::phone insteadof samsung, lg;
        }
    }

    $disney = new disneyAnimation;
    echo "Judith in zootopia ".$disney->phone()." Use it.";
?>

What if you also need to use the phone() method from another trait?
Next time, we'll learn how to use the methods of the same name in different traits.


Thank you for visiting. If you have any inquiry or explanation of mistakes, please use the comments below.


    
    

Back to the course

ALL COMMENTS 0

Sort by