1
0
mirror of https://github.com/restoreddev/phpapprentice.git synced 2025-08-03 13:27:35 +02:00

Added abstract classes page

This commit is contained in:
Andrew Davis
2018-10-10 20:35:11 -05:00
parent 97efca915c
commit ba4556cf8a
3 changed files with 55 additions and 0 deletions

View File

@@ -21,6 +21,7 @@
<li><a href="<?= page_path('classes-constructor') ?>">Classes: Constructor</a></li>
<li><a href="<?= page_path('static') ?>">Static</a></li>
<li><a href="<?= page_path('interfaces') ?>">Interfaces</a></li>
<li><a href="<?= page_path('abstract') ?>">Abstract Classes</a></li>
</ol>
<a href="<?= page_path('credits') ?>">Credits</a>
</div>

48
code/abstract.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
// Abstract classes are similar to interfaces in that they define methods that a sub-class must implement.
// However, an abstract class can also have normal methods. To create an abstract class, use the "abstract"
// keyword followed by class and the name of the class.
abstract class CellPhone
{
abstract public function unlock();
public function turnOn()
{
echo "Holding power button...\n";
}
}
// To use an abstract class, you create another class that extends it and create any methods that were marked as abstract.
// A class can only extend one abstract class and the child class has to implement all abstract methods.
class iPhone extends CellPhone
{
public function unlock()
{
echo "Touching fingerprint reader...\n";
}
}
// In this example, we use an abstract class to create the behavior for turning on a cell phone and then
// force the child classes to implement how to unlock the phone. We have clearly defined what a cell phone
// performs and we have limited code duplication.
class Android extends CellPhone
{
public function unlock()
{
echo "Typing passcode...\n";
}
}
// Our iPhone and Android classes can now both use the turnOn method and the unlock method.
$iPhone = new iPhone();
$iPhone->turnOn();
$iPhone->unlock();
$android = new Android();
$android->turnOn();
$android->unlock();
// Lastly, you cannot create an instance of an abstract class. PHP would not know how to use the abstract methods
// so when you try to create an abstract instance you will get an error.
$cellPhone = new CellPhone();

View File

@@ -141,6 +141,12 @@ return [
'title' => 'Interfaces',
'subtitle' => 'Writing code contracts',
'previous' => 'static',
'next' => 'abstract',
]),
Page::create('abstract', null, 'abstract.php', [
'title' => 'Abstract Classes',
'subtitle' => 'Inheriting an interface',
'previous' => 'interfaces',
'next' => '',
]),
],