Answer the question
In order to leave comments, you need to log in
What are abstract classes used for?
Here's a code template that everyone tries to explain the usefulness of abstract classes with:
abstract class ClassName
{
abstract public function doSomething($something);
//не абстрактные методы
}
class ChildClass extends ClassName
{
public function doSomething($something)
{
//code
}
}
class ClassName
{
//не абстрактные методы
}
class ChildClass extends ClassName
{
public function doSomething($something)
{
//code
}
}
Answer the question
In order to leave comments, you need to log in
1) You cannot instantiate an abstract class.
2) Methods declared as "abstract" are required to be implemented. That gives confidence that any successor will implement these methods.
3) Having opened a file with an abstract class, I immediately see the methods that it has, and which I need to implement. In your example, I don't know which methods relate specifically to ChildClass and which to ClassName.
All these interfaces, abstract classes, etc., are needed when several (many) people are working on the project, and the project is a little more than "your own mega-cool blog".
Try to thoroughly understand what polymorphism is, especially one of its varieties - type polymorphism.
Type polymorphism is often used in php. Here is its essence on your example:
abstract class ClassName
{
abstract public function doSomething($something);
//не абстрактные методы
}
class ChildClass extends ClassName
{
public function doSomething($something)
{
//code
}
}
class Main {
public run(ClassName $class) {
//code
}
}
$obj = new Main();
$obj->run(new ChildClass());
Encapsulation, polymorphism, etc.
I don't remember the exact terms.
You can work with different objects in the same way if you see only the base class in them.
Here you write database drivers.
accordingly, you must have an abstract driver class. which forces descendants to implement a certain set of methods, in turn, for some operations, it can offer some kind of implementation.
and then, you have, let's say, a model that needs a database driver to be passed to it.
if you have an abstract class - you can write like this: function __construct(Db_Driver $driver);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question