PHP ООП — наследование
PHP — что такое наследование?
Наследование в ООП = когда класс происходит от другого класса.
Дочерний класс унаследует все общедоступные и защищенные свойства и методы от родительского класса. Кроме того, он может иметь свои свойства и методы.
Унаследованный класс определяется с помощью extends
ключевого слова.
Давайте посмотрим на пример:
Пример
<?php
class Fruit {
public
$name;
public $color;
public
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name}
and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class
Strawberry extends Fruit {
public
function message() {
echo "Am I a fruit or a
berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
Объяснение примера
Класс Strawberry наследуется от класса Fruit.
Это означает, что класс Strawberry может использовать общедоступные свойства $name и $color, а также общедоступные методы __construct() и intro() из класса Fruit из-за наследования.
Класс Strawberry также имеет собственный метод: message().
PHP — наследование и модификатор защищенного доступа
В предыдущей главе мы узнали, что protected
доступ к свойствам или методам можно получить внутри класса и через классы, производные от этого класса. Что это обозначает?
Давайте посмотрим на пример:
Пример
<?php
class Fruit {
public
$name;
public $color;
public
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name}
and the color is {$this->color}.";
}
}
class
Strawberry extends Fruit {
public
function message() {
echo "Am I a fruit or a
berry? ";
}
}
// Try to call all three methods from outside class
$strawberry = new Strawberry("Strawberry", "red");
// OK. __construct() is public
$strawberry->message(); // OK. message()
is public
$strawberry->intro(); // ERROR. intro()
is protected
?>
В приведенном выше примере мы видим, что если мы попытаемся вызвать protected
метод (intro()) вне класса, мы получим ошибку. public
методы будут работать нормально!
Давайте посмотрим на другой пример:
Пример
<?php
class Fruit {
public $name;
public
$color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The
fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
// Call protected
method from within derived class - OK
$this ->
intro();
}
}
$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is
public
$strawberry->message(); // OK. message() is
public and it calls intro() (which is protected) from within the
derived class
?>
В примере выше мы видим, что все работает отлично! Это потому, что мы вызываем
protected
метод (intro()) из производного класса.
PHP — переопределение унаследованных методов
Унаследованные методы можно переопределить, переопределив методы (используя то же имя) в дочернем классе.
Посмотрите на пример ниже. Методы __construct() и intro() в дочернем классе (Strawberry) переопределяют методы __construct() и intro() в родительском классе (Fruit):
Пример
<?php
class Fruit {
public
$name;
public $color;
public
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name}
and the color is {$this->color}.";
}
}
class
Strawberry extends Fruit {
public $weight;
public
function __construct($name, $color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
echo "The fruit is {$this->name}, the color is {$this->color},
and the weight is {$this->weight} gram.";
}
}
$strawberry = new Strawberry("Strawberry", "red",
50);
$strawberry->intro();
?>
PHP — последнее ключевое слово
Ключевое final
слово можно использовать для предотвращения наследования классов или предотвращения переопределения методов.
В следующем примере показано, как предотвратить наследование классов:
Пример
<?php
final class Fruit {
// some code
}
//
will result in error
class
Strawberry extends Fruit {
// some code
}
?>
В следующем примере показано, как предотвратить переопределение метода:
Пример
<?php
class Fruit {
final public function intro() {
// some code
}
}
class
Strawberry extends Fruit {
//
will result in error
public function intro() {
// some code
}
}
?>