Book example: "Since the $ price property is declared in the ShopProduct class and not in BookProduct, an attempt in the code above (the BookProduct class" function getPrice () {return $this->price} ) to access it will fail. To solve this problem, you need to declare the $ price property protected and thus provide access to it to the child classes. "

 <?php class ShopProduct { public $title; public $producerMainName; public $producerFirstName; protected $price; public $discount = 0; function __construct ($title, $firstName, $mainName, $price, $discount) { // конструктор $this -> title = $title; // через $this обращаюсь к свойству этого класса title и присваиваю ему значение (аргумент), которое прилетит в переменную $title, когда вызовется метод конструктора (вызывается при создании нового объекта) $this -> producerFirstName = $firstName; $this -> producerMainName = $mainName; $this -> price = $price; $this -> discount = $discount; } /* Meтoд __construct ( ) вызывается, когда создается объект с помощью оператора new. Значения всех перечисленных аргументов передаются конструктору. Благодаря конструктору, создание экземпляров класса ShopProduct и определение значений их свойств выполняются в одном операторе. */ function getProducer () { // метод. возвр. имя и фам автора return "{$this -> producerFirstName} " . "{$this -> producerMainName}"; } function getSummaryLine () { // метод возвращает название альбома (или книги); имя, фамилию автора $base = "{$this -> title} ( {$this -> producerMainName}, "; $base .= "{$this -> producerFirstName} )"; return $base; } function setDiscount ( $num ) { // метод. задать скидку $this -> discount = $num; } function getPrice () { // метод, который принимает во внимание установленную скидку (=> цену и скидку) return ($this -> price/* - $this -> discount*/); } } /* Класс CDProduct (дочерний) расширяет возможности класса ShopProduct */ class CDProduct extends ShopProduct { function __construct ($title, $firstName, $mainName, $price) { parent:: __construct($title, $firstName, $mainName, $price); // Вызвать мeтoд __construct ( ) родительского класса $this -> playLength = $playLength; } function getPlayLength() { // метод. возвращает время звучания return $this -> playLength; } function getSummaryLine () { // метод. возвращает название альбома; имя, фамилию автора и время звучания $base = "{$this -> title} ( {$this -> producerMainName}, "; $base .= "{$this -> producerFirstName} )"; $base .= ": Время звучания - {$this -> playLength}"; return $base; } } /* Класс BookProduct (дочерний) */ class BookProduct extends ShopProduct { function getNumberOfPages () { // метод. вернуть количество страниц этого ($this) класса return $this -> numPages; } function getSummaryLine () { // метод. возвращает название книги; имя, фамилию автора и количество страниц $base = "{$this -> title} ( {$this -> producerMainName}, "; $base .= "{$this -> producerFirstName} )"; $base .= ": {$this -> numPages} стр."; return $base; } function getPrice () { return ($this -> price); } } $product = new BookProduct ("Игра престолов", "Мартин", "Джордж", "20 $", "10"); echo $product -> price; 
  • echo $product -> price; You are trying to call price from the product object . The last line here on her and swears - Kostiantyn Okhotnyk
  • "... To solve this problem, you need to declare the $ price property protected and thereby grant access to it to the child classes." The price property is called from a child class that is granted access to it. Following the logic of the written - should work. But no! - Alexander Zharichenko

1 answer 1

Protected properties ( protected ) are inaccessible outside the class as well as private ones ( private ), but unlike the latter, they can be accessed inside descendant classes.

PHP has good documentation in Russian ( http://php.net/manual/ru/language.oop5.visibility.php ), contact her when you have difficulty understanding the author of the textbook.

  • Prompted what to call as a method, not as a property. Like this: echo $ product-> getPrice (); then everything is ok! - Alexander Zharichenko
  • Although the child class inherits the price property, it cannot be called from external code. - It goes against the instructions in the book, a little confusing. Thank you - Alexander Zharichenko