Extending classes
One of the primary reasons developers use OOP is because of its ability to re-use existing code, yet, at the same time, add or override functionality. In PHP, the keyword extends
is used to establish a parent/child relationship between classes.
How to do it...
In the
child
class, use the keywordextends
to set up inheritance. In the example that follows, theCustomer
class extends theBase
class. Any instance ofCustomer
will inherit visible methods and properties, in this case,$id
,getId()
andsetId()
:class Base { protected $id; public function getId() { return $this->id; } public function setId($id) { $this->id = $id; } } class Customer extends Base { protected $name; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } }
You can force any developer using your class to define a method by marking it
abstract
. In this example, theBase
class defines asabstract
the...