კონსტრუქტორი მემკვიდრეობითობის დროს OOP-ში PHP-ში
მემკვიდრეობითობის დროს შესაძლებელია მშობელი კლასის კონსტრუქტორის გადაწერა. მოდით შევხედოთ მაგალითს. დავუშვათ, გვაქვს შემდეგი მშობელი კლასი:
<?php
class User {
private $name;
private $surn;
public function __construct($name, $surn) {
$this->name = $name;
$this->surn = $surn;
}
public function getName() {
return $this->name;
}
public function getSurn() {
return $this->surn;
}
}
?>
დავუშვათ, მშობელი კლასისგან მემკვიდრეობით მიიღება შემდეგი კლასი:
<?php
class Student extends User {
}
?>
დავუშვათ, ჩვენ გვსურს მემკვიდრე კლასში კონსტრუქტორის გაფართოება, მასში დამატებითი პარამეტრების დამატებით:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
}
}
?>
ამ შემთხვევაში ჩვენ აუცილებლად უნდა
გამოვიძახოთ მშობელი კლასის კონსტრუქტორი
პირველივე ხაზში parent::__construct()-ის მეშვეობით:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
ბრძანება parent::__construct() არსებითად არის
მშობელი კლასის კონსტრუქტორი. ამიტომ
მასში გადავცეთ საჭირო პარამეტრები:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
}
}
?>
ახლა მემკვიდრეში სწავლის წელი ჩავწეროთ მემკვიდრის საკუთარ თვისებაში:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
$this->year = $year;
}
}
?>
შევქმნათ გეთერი სწავლის წლისთვის:
<?php
class Student extends User {
private $year;
public function __construct($name, $surn, $year) {
parent::__construct($name, $surn);
$this->year = $year;
}
public function getYear() {
return $this->year;
}
}
?>
დავუშვათ, კლასი Employee მემკვიდრეობით მიიღება
ამ გაკვეთილის User კლასისგან.
გადააწერეთ Employee კლასში
მშობელი კლასის კონსტრუქტორი, მასში დამატებით
პარამეტრებით ასაკის და ხელფასისთვის.
შექმენით გეთერები ასაკისა და ხელფასისთვის.