Home  >  Article  >  Backend Development  >  What is the difference between traits and interfaces?

What is the difference between traits and interfaces?

coldplay.xixi
coldplay.xixiOriginal
2020-07-01 15:43:023725browse

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.

What is the difference between traits and interfaces?

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 = &#39;MyTrait_var&#39;;
    protected $var1 = &#39;MyTrait_var&#39;;
 
    function __construct()
    {
        echo $this->var."</br>";
    }
 
    function a()
    {
        echo "a"."</br>";
    }
}
 
interface MyInterface
{
    function __construct();
    function b();
}
 
abstract class MyAbstract
{
    protected $var2 = &#39;MyAbstract_var&#39;;
    use MyTrait;
 
    function b()
    {
        echo "b"."</br>";
    }
}
 
class MyClass extends MyAbstract implements MyInterface
{
    protected $var3 = &#39;MyClass_var&#39;;
    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:

PHP programming from entry to proficiency

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn