Home >Backend Development >PHP Problem >What is the difference between traits and interfaces?
The difference between traits and interfaces is: 1. Traits are similar to include and can be placed in the middle of the class using use. The defined methods are part of the class and cannot be instantiated directly; 2. The methods in the interface are Virtual, these methods need to be redefined when inheriting.
The difference between traits and interfaces is:
1, trait
looks more like It is a small plug-in written for code reuse. It is similar to include. You can use use to place it in the middle of a class, so that the methods defined in the trait are part of the class and cannot be instantiated directly.
2. The methods in interface
are all virtual, and these methods need to be redefined when inheriting. In other words, the methods are descriptive in nature and do not have actual operations. When you inherit, you need to implement these methods, otherwise errors will occur and cannot be missing. Interfaces are often used in architecture to abstractly define the properties and methods owned by an instance. To put it simply, it is like an agreement, a task assigned by the boss. If you want to inherit, you must meet this agreement, that is, complete the tasks assigned by your boss.
<?php trait MyTrait { protected $var = 'MyTrait_var'; protected $var1 = 'MyTrait_var'; function __construct() { echo $this->var."</br>"; } function a() { echo "a"."</br>"; } } interface MyInterface { function __construct(); function b(); } abstract class MyAbstract { protected $var2 = 'MyAbstract_var'; use MyTrait; function b() { echo "b"."</br>"; } } class MyClass extends MyAbstract implements MyInterface { protected $var3 = 'MyClass_var'; function c() { echo "c"."</br>"; } } $class = new MyClass(); $class->a(); $class->b(); $class->c();
In the above code, the function b()
in MyAbstract can also be placed in MyClass
, or the interface MyInterface
# can be implemented by MyAbstract
##Related learning recommendations:
The above is the detailed content of What is the difference between traits and interfaces?. For more information, please follow other related articles on the PHP Chinese website!