Traits vs. interfaces

前端 未结 13 1236
傲寒
傲寒 2020-11-28 17:09

I\'ve been trying to study up on PHP lately, and I find myself getting hung up on traits. I understand the concept of horizontal code reuse and not wanting to necessarily in

13条回答
  •  攒了一身酷
    2020-11-28 17:46

    For beginners above answer might be difficult, this is the easiest way to understand it:

    Traits

    trait SayWorld {
        public function sayHello() {
            echo 'World!';
        }
    }
    

    so if you want to have sayHello function in other classes without re-creating the whole function you can use traits,

    class MyClass{
      use SayWorld;
    
    }
    
    $o = new MyClass();
    $o->sayHello();
    

    Cool right!

    Not only functions you can use anything in the trait(function, variables, const...). Also, you can use multiple traits: use SayWorld, AnotherTraits;

    Interface

      interface SayWorld {
         public function sayHello();
      }
    
      class MyClass implements SayWorld { 
         public function sayHello() {
            echo 'World!';
         }
    }
    

    So this is how interfaces differ from traits: You have to re-create everything in the interface in an implemented class. Interfaces don't have an implementation and interfaces can only have functions and constants, it cannot have variables.

    I hope this helps!

提交回复
热议问题