The difference between traits, interfaces, abstract of

<?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();

The above code, MyAbstract the function b () can also be placed in MyClass, or implemented by the interfaces MyInterface MyAbstract.

  . 1) looks more like trait to a small plug multiplexing written code, which is similar to the include, use may be in the middle class, so the method defined inside trait as part of the class itself can not be instantiated directly.
  2) interface which methods are virtual, the need for re-definition of these methods in the succession of time. That is, by nature, and not the actual operation, and you inherited when the need to implement these methods, otherwise it will go wrong, and can not be missing. often used when the interface architecture, one example of the properties and methods have abstract definitions. Simply put, a similar agreement, boss assigned the task. You have to inherit, you must meet the agreement, which is to complete the tasks assigned by the owner.
  3) abstract: When a is applied to the abstract class, which is defined as an abstract class, inheritance can only be used, the object can not be instantiated. An abstract class may not contain abstract methods, but there must be an abstract method in the abstract class and subclasses of this abstract class abstract method must be fully realized, otherwise, should be identified as a subclass of an abstract class. Abstract method inherited by subclasses must be implemented, it can not go abstract abstract methods defined by private modifier, can be used to modify the public and protected.

Guess you like

Origin www.cnblogs.com/Mr-Echo/p/12152239.html