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 ...
Get PHP 7: Real World Application Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.