Well, using your Car object, I'll try to explain the concept with a real world example.
Imagine, you're a little company (A) which makes car pieces, you make them for a bigger company (B) which is your client, that pieces will be used by other car constructors.
The company B must be sure that your pieces will follow a standard and will be compatible within all car constructors.
It is your interface.
Interfaces are used to define some standardized methods or attributes, taking our example, we can define that a piece has 4 holes in each corners to be fixed on another pieces made by another company.
An abstract is a little different, abstract are more concrete than interface (well I agree that's a kind of non-sense), but they are concret because they directly implements (for example an interface) a functionality whereas that Abstract class can never be instantiated.
Abstract class are mostly used to define some basic or shared functionality to make it DRY.
Therefore, you may create a Class which extends an Abstract class AND implements an interface.
Here is an example:
interface Vehicle {
protected $engine;
protected $wheels;
public function startUp();
public function stop();
}
Your Vehicle interface define a Vehicle which needs to have an engine and wheels (any number).
abstract class Car implements Vehicle {
protected $wheels = 4;
public function startUp() {
$this->engine->startUp();
}
public function stop() {
$this->engine->stop();
}
}
Because startUp()
and stop()
are just a proxy to the Engine object, we can put them in the abstract class to be reused in all the extended classes.
We set our Car class to have 4 wheels.
class Renault extends Car {
protected $color = 'yellow';
}
Here we just need to extend the Car abstract class, we add some color because it's cool.
Now, let's say that we want to bring our Renault to a car washing station, because we're implementing a known interface, the car washing station will be able to make its work without knowing that our Vehicle is Renault, but just knowing it is a Vehicle.
That's a really basic example, and it could be better designed but it should show you how it works.
Interfaces are not needed, at least PHP doesn't require any class to implements any Interface, however, you should use them, it is often a good practices and it helps you when writing API, Unit tests or sharing some code amongst other developers.