You can use
traits implement
interfaces and extend
abstract classes.
Here are some notes on how they are different and how to use them for better code design.
TLDR;
Use Interfaces as a Public Contract;
Use Abstract Classes as a Private Contract;
Use Traits as Class Extensions;
Traits will override abstract class methods;
Here are some ways to think of traits, interfaces, and abstract classes to write better php—
- Interface === Type
- Use it to declare a public contract
It is a type, a new type of object. An abstract type.
It is similar to an abstract class but
It is not a contract, but we can make it a contract by pre-declaring its public behavior
- Use it to declare a private contract
While Interfaces declare a public contract, abstract classes can declare a private contract
- Traits are just like classes
- Use it as class extensions
A trait can do anything a normal php class can do except
Methods in a trait are overwritable. You can change
use MyTrait {
MyTrait::method as private differentMethodName;
MyTrait::doSomething as public reallyDoSomething;
}
All data/properties in a Trait are calculated at runtime
__CLASS__
will always be the class that is using the Trait.Trait methods will override methods in an Abstract Class.
trait MyTrait
{
public function doSomething()
{
return 'trait wins!';
}
}
abstract class MyAbstractClass
{
public function doSomething()
{
return 'abstract class wins!';
}
}
class MyClass extends MyAbstractClass
{
use MyTrait;
}
$test = new MyClass();
echo $test->doSomething();
// This prints 'trait wins!'
Starting In PHP 8.0, Traits can now have abstract private
methods.
abstract private
methods can be used as contracts.abstract private
in an abstract class.Starting In PHP 8.1, You can override constants defined by Interfaces.