Created
November 4, 2022 07:27
-
-
Save nitrotap/312e89233ba442341fea483f26123f0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// abstracted code | |
// create the abstract class | |
// basically a class that says any child classes need a method called get_drink_name and a variable called _drink_state | |
abstract class HotDrinksAbstract | |
{ | |
abstract function get_drink_name(); | |
// now if anyone else uses the HotDrinksAbstract Class, they will all have to specify a get_drink_name function | |
protected $_drink_state = 'hot'; | |
// now all child classes will have the variable _drink_state available to them, and it will return hot | |
// no point in having a private function/variable since it won't be available in child classes | |
} | |
// hot cocoa example demonstrating the protected variable from the abstract class | |
class AbstractHotCocoa extends HotDrinksAbstract | |
{ | |
public function get_drink_name() | |
{ | |
return "The best $this->_drink_state chocolate of your life <br/> "; | |
} | |
} | |
echo 'Abstracted Code - Hot Cocoa: <br/>'; | |
$hot_cocoa = new AbstractHotCocoa(); | |
print_r($hot_cocoa->get_drink_name()); | |
// latte example demonstrating overriding the protected variable from the parent class | |
class AbstractLatte extends HotDrinksAbstract | |
{ | |
protected $_drink_state = 'cold or hot'; | |
// the initial protected class can be overridden in the child class | |
// this class MUST HAVE a function get_drink_name() | |
public function get_drink_name() | |
{ | |
return "Lattes are good $this->_drink_state <br/> "; | |
} | |
} | |
echo '<br/> Abstracted Code - Latte: <br/>'; | |
$_latte = new AbstractLatte(); | |
print_r($_latte->get_drink_name()); | |
// ---------------------------------------- | |
// your code | |
echo '<br/> Your code: <br/>'; | |
class HotDrinks | |
{ | |
public $drink; | |
function __construct($drink) | |
{ | |
$this->drink = $drink; | |
} | |
function get_drink() | |
{ | |
return $this->drink; | |
} | |
} | |
$drink = new HotDrinks("Latte"); | |
echo $drink->get_drink(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment