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...

  1. In the child class, use the keyword extends to set up inheritance. In the example that follows, the Customer class extends the Base class. Any instance of Customer will inherit visible methods and properties, in this case, $id, getId() and setId():
    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 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.