am wondering when should I use the abstract? I've been digging for a simple code example in google but couldn't find any .. BTW I discovered 'abstract' just an hour ago while am learning PHP .. may someone please post a simple example for me ? thank you
Asked
Active
Viewed 65 times
0
-
1https://www.php.net/manual/en/language.oop5.abstract.php – Jeto Apr 17 '21 at 22:14
-
Lets say you write 2 separate classes and it seems like you are reusing same logic in both of them as a method, well you can just create an abstract class for that to keep everything more compact and maintainable. – Areg Apr 17 '21 at 22:58
-
@Areg so you mean it just reduces the code ? – Wael Apr 18 '21 at 00:28
-
4Does this answer your question? [What is an abstract class in PHP?](https://stackoverflow.com/questions/2558559/what-is-an-abstract-class-in-php) – Reece Apr 18 '21 at 02:07
1 Answers
0
Inside abstract class you can use abstract methods. So, you can use it in usual methods. And concrete childs of abstract class have to implement abstract methods.
abstract class AbstractDonator
{
public function donateMinimum(): void
{
// this method can be complex
$minimum = 10;
$this->donate($minimum)
}
abstract protected function donate(int $money);
}
class ConcreteDonatorOne
{
protected function donate(int $money)
{
$donateProvider = new PlayPal();
$donateProvider->pay($money);
}
}
class ConcreteDonatorTwo
{
protected function donate(int $money)
{
$donateProvider = new Scribe();
$donateProvider->transfer($money);
}
}
$donators = [
new ConcreteDonatorOne(),
new ConcreteDonatorTwo(),
];
foreach ($donators as $donator)
{
$donator->donateMinimum();
}

Виктор 78
- 21
- 2