OOP Constructor oroklodese
Kezdo vagyok OOP teren. Elolvastam par dokumentaciot, de valamit nem igazan ertek! Itt van a kovetkezo kod:es itt van a gyerek (child) class amely orokol mindent a ShopProduct-tol. A constructort is orokli!
Na most en szeretnek egy sajat consztruktort letrehozni a gyerek class-ban.Azt nem ertem, hogy miert kell ertesiteni a szulot a kovetkezo kodal ? Ha nem ertesitem a gyerek elveszti azokat a constructor adatokat amiket orokol az apatol?
Koszonom!
■ - class ShopProduct {
- public $title;
- public $producerMainName;
- public $producerFirstName;
- public $price;
- function __construct( $title, $firstName, $mainName, $price ) {
- $this->title = $title;
- $this->producerFirstName = $firstName;
- $this->producerMainName = $mainName;
- $this->price = $price;
- }
- function getProducer() {
- return "{$this->producerFirstName}". " {$this->producerMainName}";
- }
- function getSummaryLine() {
- $base = "{$this->title} ( {$this->producerMainName}, ";
- $base .= "{$this->producerFirstName} )";
- return $base;
- }
- }
Na most en szeretnek egy sajat consztruktort letrehozni a gyerek class-ban.
- class CdProduct extends ShopProduct {
- public $playLength;
- function __construct($title, $firstName, $mainName, $price, $playLength) {
- parent::__construct($title, $firstName, $mainName, $price);
- $this->playLength = $playLength;
- }
- function getPlayLength() {
- return $this->playLength;
- }
- }
- parent::__construct($title, $firstName, $mainName, $price);
Koszonom!
RTFM
Tehát automatikusan nem hívódik meg a szülő konstruktora.
ok
OOP elv megsertese
mert te
Mert te tudod, hogy a származtatott konsturktorban mikor akarod meghívni a szülő konstruktorát (elején/végén), ez esetfüggő.
illik a szülő konstruktorát meghívni először
Ezért bizonyos nyelvek esetén (ha jól rémlik, akkor talán C++, de ebben bőven nem vagyok bizots) a fordító sír is, ha nem az első sor az ős konstruktotának meghívása, vagy automatikusan meghívja, ha nem az lenne (pl. java, ha van paraméter nélküli konstruktora az ősnek).
Üdv,
Felhő