Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Traits in PHP?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 113
    Comment on it

    Traits in php are the mechanism for reusing the code in a single inheritance.

    Trait is as similar as a class, but only focus to group functionality in a consistent way to fine grained. We can not instantiate a Trait . It is for reducing some limitations of single inheritance for reusing group of methods easily in different independent classes in a different class hierarchies.

    We can do Multiple Traits insertion into a class by listing all in the use statement, and separated them by commas.Please note that If we insert two Traits having method with the same name, then a fatal error is produced.

    Example

    class BaseClass{
        function getReturnType() {
            return 'BaseClass';
        }
    }
    trait traitSample {
        function getReturnType() {
            echo "TraitSample:";
            parent::getReturnType();
        }    
    }
    
    class Class1 extends BaseClass {
        use traitSample;   
    }
    
    $obj1 = new Class1();
    $obj1->getReturnType();//TraitSample:BaseClass
    

 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: