Answer the question
In order to leave comments, you need to log in
How is the implementation of an interface chosen?
Tell me, how is the choice of interface implementation when one interface is implemented by several classes?
Let's say we have a machine interface
interface ICar {
start();
stop();
}
class Sportcar implements ICar {
start() {
/**/
}
stop() {
/**/
}
//nitro() {
// /**/
//}
}
class Bus implements ICar {
start() {
/**/
}
stop() {
/**/
}
//openDoor() {
// /**/
//}
}
function startCar(ICar $car) {
$car->start();
Answer the question
In order to leave comments, you need to log in
An interface should not be treated as a data type. You are not calling an interface method, you are calling a method on a class that inherits from the interface. You do not create an object of type ICar. You create an object of type Sportcar and you access the object of type Sportcar through the ICar interface methods.
The runtime knows which implementation (Bus or Sportcar) is behind ICar and it
calls the methods of this class.
This is so because at the beginning of the memory where this object is located, its type is indicated (Bus or Sportcar).
upd.
Roughly speaking, it is not clear to me in which case, when using the ICar $car variable, the Sportcar object will be obtained, and in which Bus object?
Or is it better to immediately get a variable like Sportcar or Bus, and use the interface only for standardization?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question