Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Changing accessibility of trait method

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 185
    Comment on it

    Hello Readers!

    Today, We will discuss about the PHP 5.4 new feature trait and it's method accessibility/visibility. A trait is similar to a class. It is used to reduce the duplication of the code. But a trait cannot instantiate on its own.
    You can also change the visibility of the method in the exhibiting class.

     

    Following example for accessibility of trait:

    <?php
    trait test
    {
        private function xyz()
        {
            echo "xyz function within trait <b>test</b><br/>";
        }
    }
    
    class Abc
    {
        use test { test::xyz as public; } //changing accessibility of function xyz
    }
    
    class Def
    {
        use test { test::xyz as public changeName;} //alias name to function.
    }
    
    
    $obj1 = new Abc;  //object of Abc created
    
    $obj1-> xyz();   //trait function called.
    
    $obj2 = new Def;  //object of Def created
    
    $obj2-> changeName(); //trait function called with alias name.
    
    ?>


    In the above example we have created a trait function with private accessibility. In class Abc we have changed the accessibility of the function from private to public using the as syntax. Also we can give the alias name to the existing function and then can access the function with that alias name like we have done same work the class Def. We have given the name changeName to the existing function xyz and then after creating object we called the function by alias name.

    Hope I have cleared my point about trait accessibility. If you have any query about trait please write the comment for the same. I will give you answer for this.

    --
    Thanks,
    Vipul

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: