Новый комментарий

SlipKnot 13.07.2018 в 09:23

Домашка:

class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($text, $title, $homework);
        $this->price = $price;
    }
    public function getPrice()
    {
        return $this->price;
    }
    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании PHP', 'лол, кек, чебурек',
    'Домашка: ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);

UPD: что такое "void"? Мы вроде такого не проходили. Или дайте ссылку где прочитать

ivashkevich 14.07.2018 в 09:28

Отлично!
А void - значит что функция ничего не возвращает.

Galay 19.07.2018 в 14:44
class PaidLesson extends Lesson {
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price) {
        parent:: __construct ($title, $text, $homework);
        $this->price = $price;
        }
    public function getPrice()
            {
                return $this->price;
            }
    public function setPrice(): void 
            {
                $this->price = $price;
            }
}
$pideLesson = new PaidLesson('Урок о наследовании в PHP','Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($pideLesson);
ivashkevich 21.07.2018 в 06:17

Отлично!

Invo 24.06.2019 в 14:15

а разве setPrice - не должен принимать саму цену?

Ilon 01.08.2018 в 09:56
Class PaidLesson extends Lesson{
    private $price;

    public function __construct($title, $text, $homework, $price){
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price):void {
        $this->price = $price;
    }
    public function getPrice(){
        return $this->price;
    }
}

$paidlesson = new PaidLesson("Урок о наследование в PHP", "лол, кек, чебурек", "Повторение мать учение!!!", "445,5 рубль");

echo "<br>";
echo "<pre>";
var_dump($paidlesson);
echo "</pre>";
ivashkevich 03.08.2018 в 15:35

Всё норм, кроме, опять же, типов аргументов - их нужно указывать. Так не пишут уже пару лет.
И строки без переменных в них нужно писать в одинарных кавычках.

Ilon 08.08.2018 в 11:37

Я писал типов аргументов, но PHPStorm выдает подсказку, это устарело и его использовали ниже версии 7. Так писать или нет?)

ivashkevich 10.08.2018 в 19:54

Не мог он такую подсказку дать, он говорит, что в Ваших настройках PHPStorm указана версия PHP < 7, а типы появились позже. Нужно зайти в настройки PHPStorm в пункт PHP и выбрать правильную версию.

Ilon 13.08.2018 в 14:05

Извиняюсь, английский не очень у меня, не правильно понял))

ivashkevich 13.08.2018 в 15:32

Ничего страшного, главное чтобы Вы на новой версии учились =)

computerix 30.08.2018 в 12:47
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class PaidLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = =$price;
    }
}   
$lesson = new Lesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($lesson);
ivashkevich 01.09.2018 в 13:30

Отлично!

DmitryGavrilov 14.09.2018 в 11:08
class PaidLesson extends Lesson {

    private $price;

    public function __construct( string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice() {
        return $this->price;
    }

    public function setPrice(float $price) {
        $this->price = $price;
    }

}

$paidLesson  = new PaidLesson('Урок о наследование PHP', 'Лол,кек,чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 22.09.2018 в 19:48

Отлично!

artemjeka 14.09.2018 в 17:11
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
$paidLesson->setPrice(55.234);
$paidLesson->setTitle('Новый title!');
$paidLesson->setText('Новый text!');
$paidLesson->setHomework('Новый homework!');
var_dump($paidLesson);

//object(PaidLesson)[1]
  //private 'price' => float 55.234
  //private 'homework' (Lesson) => string 'Новый homework!' (length=20)
  //protected 'title' => string 'Новый title!' (length=17)
  //protected 'text' => string 'Новый text!' (length=16)
ivashkevich 22.09.2018 в 19:48

Всё супер!

Benya 28.09.2018 в 20:53
class PaidLesson extends Lesson
{
    private $price;

    public function __construct($title, $text, $homework, $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paid = new PaidLesson('Урок о наследовании в PHP', ' Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.9');
var_dump($paid);
ivashkevich 28.09.2018 в 23:15

Отлично!

SBTesla 04.10.2018 в 11:55
class PaidLesson extends Lesson {
     protected  $prise;

     public function __construct(string $title, string $text, string $homework, string $prise)
     {
          parent::__construct($title, $text, $homework);
          $this->prise = $prise;
     }

     public function getPrise():float {
          return $this->prise;
     }
     public function setPrise($prise): void
     {
          $this->prise = $prise;
     }
}

$PaidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее','цена:99.90');
var_dump($PaidLesson);
ivashkevich 06.10.2018 в 14:24

Хорошо, только price через c.

AxLT 12.10.2018 в 20:30

Отличный курс, все доступно и понятно.

class PayLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homeWork, float $price)
    {
        parent::__construct($title, $text, $homeWork);
        $this->price = $price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }
}

$payLess = new PayLesson
(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90
);
var_dump($payLess);
ivashkevich 13.10.2018 в 21:17

Отлично! И спасибо =)

AntonM99 04.11.2018 в 10:39
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$pLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($pLesson);
ivashkevich 04.11.2018 в 13:52

Отлично!

zebra 04.11.2018 в 13:36

Домашка:)

 class PaidLesson extends Lesson
 {
     private $price;

     public function __construct(string $title, string $text, string $homework, float $price)
     {
         parent::__construct($title, $text, $homework);
         $this->price = $price;
     }

     public function setPrice(float $price): void
     {
         $this->price = $price;
     }

     public function getPrice()
     {
         return $this->price;
     }
 }

 $paidLesoon = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудрене', 99.90);
 var_dump($paidLesoon);
ivashkevich 04.11.2018 в 13:53

Отлично!

Todd 04.11.2018 в 19:08
<?php
class PaidLesson extends Lesson {

    private $price;

    public function __construct(string $title, string $text, string $homework, float $price) {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(float $price): void {
        $this->price = $price;
    }

    public function getPrice(): float {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

debug($paidLesson);
?>
ivashkevich 04.11.2018 в 19:17

Хорошо, но переноси открывающие скобки { для классов и методов на новые строки.

stokato 05.11.2018 в 22:00

Создайте ещё один класс, являющийся наследником класса Lesson - PaidLesson (платный урок).
Объявите в нем свойство price (цена), а также геттеры и сеттеры для этого свойства. Добавьте в конструкторе параметр, через который это свойство будет устанавливаться при создании объекта.
Создайте объект этого класса со следующими свойствами:
заголовок: Урок о наследовании в PHP
текст: Лол, кек, чебурек
домашка: Ложитесь спать, утро вечера мудренее
цена: 99.90
Выведите этот объект с помощью var_dump()

<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($lesson);
ivashkevich 05.11.2018 в 22:15

Отлично!

Moskva 10.11.2018 в 11:26
    class PaidLesson extends Lesson
    {
        private $price; 
        public function __construct(string $title, string $text, string $homework, string $price)
        {
            parent::__construct($title, $text, $homework); // позваляет унаследовать переменные в this из родительского класса
            $this->price = $price;
        }
        public function getPrice(): string
        {
            return $this->$price;
        }
        public function setPrice(string $price): void 
        {
            $this->price = $price;
        }   
    }
    $message = new PaidLesson('Урок о наследовании PHP', 'лол, кек, чебурек',
    'Домашка: ложитесь спать, утро вечера мудренее', 99.90);
    var_dump($message);
ivashkevich 12.11.2018 в 01:50

Отлично!

bildep 18.11.2018 в 15:15
<?php
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__conctruct($title, $text, $homework);
        $this->setPrice($price);

    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($lesson);

ошибка выходит Fatal error: Uncaught Error: Call to undefined method Lesson::__conctruct() in

ivashkevich 19.11.2018 в 21:44

Это из-за опечатки в написании: __conctruct, а должно быть __construct.

И обратите внимание, что где-то в конструкторе вы задаете свойства через сеттеры, а где-то напрямую пишете в свойства. Как именно делать - решать вам, но делайте это одинаково.

[email protected] 24.11.2018 в 18:29
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
echo '<pre>';
var_dump($lesson);
echo '</pre>';
ivashkevich 24.11.2018 в 21:57

Супер!

Waldemar 30.11.2018 в 02:06
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$PaidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($PaidLesson);
ivashkevich 30.11.2018 в 23:16

Супер!

Waldemar 30.11.2018 в 02:09

Решил в ОпенСервере сменить PHP с 7.0 на 7.2, и var_dump вывелся в сплошную строку:

object(PaidLesson)#1 (4) { ["price":"PaidLesson":private]=> float(99.9) ["homework":"Lesson":private]=> string(67) "Ложитесь спать, утро вечера мудренее" ["title":protected]=> string(43) "Урок о наследовании в PHP" ["text":protected]=> string(30) "Лол, кек, чебурек" }

ivashkevich 30.11.2018 в 23:17

В 7.2 у OpenServer отсутствует XDebug. Это именно он формирует красивый вывод var_dump.

iluha22 18.10.2019 в 08:30

Оберни var_dump в теги <pre>...</pre>

CarfikDK 16.12.2018 в 16:06

Спасибо за урок!
У меня есть вопрос: "var_dump();" у меня выводится строкой, а не акуратно столбиком как у вас, как это можно решить?

<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework )
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework() : string
    {
        return $this->homework;
    }

    public function setHomework(string $homework) : void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice() : float
    {
        return $this->price;
    }

    public  function  setPrice() : void
    {
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании PHP', 'Лол, кек, чебурек', 'Сон для слабакооов!!', '99.90');

var_dump($lesson);
ivashkevich 16.12.2018 в 18:17

За это отвечает расширение xdebug. Инструкция тут

CarfikDK 17.12.2018 в 13:41

Совсем забыл настроить Xdebug поле того как скачал PHPstorm из телеграм чата. Огромное спасибо! А как само ДЗ?

ivashkevich 17.12.2018 в 13:48

Что-то не выводится цена.

CarfikDK 17.12.2018 в 14:48

Исправил

<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework )
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework() : string
    {
        return $this->homework;
    }

    public function setHomework(string $homework) : void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice() : float
    {
        return $this->price;
    }

    public  function  setPrice(float $price) : void
    {
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании PHP', 'Лол, кек, чебурек', 'Сон для слабакооов!!', '99.90');
var_dump($lesson);
ivashkevich 17.12.2018 в 15:29

Другое дело :)

[email protected] 20.12.2018 в 16:10
class PaidLesson extends Lesson
{
    public $price;

    function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 20.12.2018 в 17:42

Супер!

alepawka 01.01.2019 в 13:36
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title,$text,$homework);
        $this -> price = $price;
    }
    public function SetPrice($price) {
        $this -> price = price;
    }
    public function GetPrice() {
        return $this ->price;
    }
}
$lessPHP = new PaidLesson('Урок по наследованию PHP','Лол,кек,чебурек','Ложись спать!','99.90');
var_dump($lessPHP);
ivashkevich 01.01.2019 в 15:47

Ок. Имена методов должны начинаться с маленькой буквы. Для цены указали тип float и явно передаёте строку - почему не число?

landialog 01.01.2019 в 17:29
class PaidLesson extends Lesson
{
    private $price;
    public function __construct($title, $text, $homework, $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price)
    {
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
}

$plesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($plesson);

P.S. Опять этот вопрос по поводу использования типов данных. Где-то в документации по PHP прочитал что добавлением псевдотипов данных используется с PHP 7.1 как подсказка для программистов.
Правда это? Или еще есть др. объяснение, в качестве доп. защиты данных?
К слову сказать в PhpStorme(установлена последняя версия) есть подсказки написания геттеров и сеттеров и там почему-то не добавляет эти доп. данные?

ivashkevich 01.01.2019 в 18:02

Посмотри урок про функции из курса PHP для начинающих.

Bogdan 02.01.2019 в 19:23

Объявите в нем свойство price (цена), а также геттеры и сеттеры для этого свойства. Добавьте в конструкторе параметр, через который это свойство будет устанавливаться при создании объекта.

<?php
include "Lesson.php";

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
}

Создайте объект этого класса со следующими свойствами:
заголовок: Урок о наследовании в PHP
текст: Лол, кек, чебурек
домашка: Ложитесь спать, утро вечера мудренее
цена: 99.90

<?php
include "PaidLesson.php";

$paidLesson1 = new PaidLesson(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90);

Выведите этот объект с помощью var_dump()

var_dump($paidLesson1);
  1. Большое спасибо за эти уроки, до этого изучал давненько Java, как бы ООП язык, но о ООП знал "слышу звон, не знаю где он", неуверенно себя чувствовал. НО сейчас очень много точек расставилось над i.
  2. в Java вроде было правило, что файл должен иметь название идентичное названию класса, есть ли вообще такое правило, и применяется ли оно к РНР?. Спасибо
ivashkevich 02.01.2019 в 21:56

По коду всё хорошо. По правилу именования - да, есть такое, дальше по курсу будет.

Pavel-Tonk 24.01.2019 в 23:48

У меня у одного ошибка при выполнении метода класса Post:

    public function setText($text):void
    {
        $this->text = $text;
    }

когда пытаюсь использовать сеттер,
Fatal error: Uncaught TypeError: Return value of Post::setText() must be an instance of void, none returned in W:\domains\myproject.loc\www\index.php:26 Stack trace: #0 W:\domains\myproject.loc\www\index.php(51): Post->setText('\xD0\x98\xD0\xB2\xD0\xB5\xD0\xBD\xD0\xB5\xD1\x86\xD0\xBA\xD0...') #1 {main} thrown in W:\domains\myproject.loc\www\index.php on line 26.
Как я понял ожидается возврат любого значения, из-за void, но его не происходит, т.к. нам return не нужен.

Pavel-Tonk 24.01.2019 в 23:54

Вопрос решен=) Переключился на версию PHP 7.1. Оставлю комент, вдруг кому понадобится!

ivashkevich 25.01.2019 в 10:10

ОК)

Bugaga159 02.02.2019 в 09:51
class PaidLesson extends Lesson
{
    protected $price;

    public function __construct( string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;

    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 03.02.2019 в 23:47

Отлично. А почему поле цены с типом protected?

Bugaga159 04.02.2019 в 20:29

Да, я тут ошибся, нужно было private.

excent63 03.02.2019 в 17:53

Спасибо за урок!
Это задание понял вот так:

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): string
    {
        return $this->price;
    }
    public function setPrice(string $price): void
    {
        $this->price = $price;
    }
}
$paidLesson = new PaidLesson('Урок о наследовании PHP','Лол,кек,чебурек','Ложитесь спать, утро вечера мудренее', '99,90');
var_dump($paidLesson);
ivashkevich 03.02.2019 в 23:48

Цену всё-таки принято хранить в виде чисел, а не строк.

excent63 06.02.2019 в 21:03

Теперь до конца понял как лучше применять строки, или числа. Спасибо!

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$paidLesson = new PaidLesson('Урок о наследовании PHP','Лол,кек,чебурек','Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 07.02.2019 в 13:50

Ок!

cap 25.02.2019 в 00:16
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
       return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidlesson1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($paidlesson1);
ivashkevich 25.02.2019 в 10:38

Ок. А почему в конструктор последний аргумент строкой передаешь?

Evgeny 10.03.2019 в 15:52

<?php

class Post
{

    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }

    public function getText(): string
    {
        return $this->text;
    }

    public function setText(string $text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{

    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLession extends Lesson
{

    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidlession = new PaidLession('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее',
    99.90);
var_dump($paidlession);
ivashkevich 11.03.2019 в 21:13

Отлично!

[email protected] 17.03.2019 в 17:47
class PaidLesson extends Lesson
{
    private $price;

    function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;

    }

    function setPaid(float $price) : void
    {
        $this->price = $price;
    }

    function getPaid(): float
    {
        return $this->price;
    }
}
include 'PaidLesson.php';
$paid = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paid);
ivashkevich 17.03.2019 в 23:56

Отлично

85bogdan45 17.03.2019 в 18:18

Если при выполнении домашки в классе Lesson модификатор доступа оставить private $homework; то результат выдает вот такой, но это же неверно? Не совсем понимаю что должно сломаться в этом случае

object(PaidLesson)[1]
  private 'price' => float 99.9
  private 'homework' (Lesson) => string 'Ложитесь спать, утро вечера мудренее' (length=67)
  protected 'title' => string 'Урок о наследовании в PHP' (length=43)
  protected 'text' => string 'Лол, кек, чебурек' (length=30)

Нужно изменить на protected $homework; и тогда результат получится вот такой:

object(PaidLesson)[1]
  private 'price' => float 99.9
  protected 'homework' => string 'Ложитесь спать, утро вечера мудренее' (length=67)
  protected 'title' => string 'Урок о наследовании в PHP' (length=43)
  protected 'text' => string 'Лол, кек, чебурек' (length=30)
ivashkevich 17.03.2019 в 23:57

Через публичные геттеры и сеттеры родительского класса можно достучаться до его приватных свойств.

mitja1211 19.03.2019 в 12:15
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price)
    {
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
}
$PaidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($PaidLesson);
ivashkevich 19.03.2019 в 23:26

Хорошо. А почему в Post и Lesson свойства protected, а в PaidLesson private?

mitja1211 20.03.2019 в 06:00

Потому что свойство price принадлежит классу PaidLesson, а от этого класса никто не наследует.правильно?

ivashkevich 20.03.2019 в 10:02

Верно =)

Grewi 28.03.2019 в 23:26
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice():float
    {
        return $this->price;
    }

    public function setPrice(float $price):void
    {
        $this->price = $price;
    }
}

$PaidLesson = new PaidLesson('Урок о наследовании в PHP','Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',99.9);

var_dump($PaidLesson);
ivashkevich 29.03.2019 в 16:29

Отлично

Boodoo 09.04.2019 в 19:58
<?php
    class PaidLesson extends Lesson
    {
        private $price;

        public function __construct(string $title, string $text, string $homework, string $price)
        {
            parent::__construct($title, $text, $homework);
            $this->price = $price;
        }
        public function getPrice() : string
        {
            return $this->price;
        }
        public function setPrice($price) : void
        {
            $this->price = $price;
        }
    }

    $paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
    var_dump($paidLesson);
ivashkevich 09.04.2019 в 21:00

Почему у вас цена - это строка? В сеттере тоже должен быть тип.

Boodoo 10.04.2019 в 06:17
class PaidLesson extends Lesson
    {
        private $price;

        public function __construct(string $title, string $text, string $homework, float $price)
        {
            parent::__construct($title, $text, $homework);
            $this->price = $price;
        }
        public function getPrice() : string
        {
            return $this->price;
        }
        public function setPrice(float $price) : void
        {
            $this->price = $price;
        }
    }

    $paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
    var_dump($paidLesson);
ivashkevich 10.04.2019 в 15:19

Ок

polvanovv 18.04.2019 в 06:36
class  PaidLesson extends  Lesson
{
    private $price;

    public function __construct(string $title,string $text,string $homework,string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;

    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice( string $price): void
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 
'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($paidLesson);

Если в родителях указаны типы переменных надо ли повторяться в наследниках или такая запись тоже верна?

public function __construct($title, $text, $homework,string $price)
ivashkevich 18.04.2019 в 07:34

Всё у вас верно. При вызове метода мы не указываем тип аргументов, тип указывается только в описании метода.
А вот price должен иметь тип float.

Dram 28.04.2019 в 19:15

Разобрался, так правильнее

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }

}

$platno = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($platno);
ivashkevich 29.04.2019 в 11:43

Отлично!

artemship 06.05.2019 в 17:28
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

}

$paidLesson = new PaidLesson(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90
);
var_dump($paidLesson);
ivashkevich 10.05.2019 в 13:27

Образцовая домашка

Tina 09.06.2019 в 13:53

Домашка "Наследование"

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($paidLesson);
ivashkevich 09.06.2019 в 18:25
public function getPrice()

нужно указать возвращаемый тип.

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

Параметр float, а передаёте зачем-то строку.

Tina 09.06.2019 в 19:00

Спасибо, поняла ошибку

ivashkevich 10.06.2019 в 03:01

Отлично

ashfedor 09.06.2019 в 18:32
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    /**
     * @return mixed
     */
    public function getPrice(): float
    {
        return $this->price;
    }

    /**
     * @param mixed $price
     */
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90
);
var_dump($paidLesson);
ivashkevich 09.06.2019 в 18:41
public function getPrice()

нужно указать возвращаемый тип.

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

Параметр float, а передаёте зачем-то строку.

ashfedor 09.06.2019 в 20:16

Понял! поправил

ivashkevich 10.06.2019 в 03:00

Отлично

Bocha 13.06.2019 в 16:36

Артем, спасибо за урок!
Есть вопрос:
В классе Lesson оставляю модификатор доступа к свойству 'homework' как 'private' и все выводится без ошибок, однако, судя по тексту урока, я не должен был получить доступ к этому свойству из наследуемого класса (т.к. 'private', а не 'protected'). Увидел комментарий выше о том, что через публичные геттеры и сеттеры можно достучаться до частных свойств родительского объекта. Это именно тот случай или у меня где-то закралась ошибка? Как делать правильнее и на что это влияет (скорость, безопасность, качество кода и т.д.)?

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->titile;
    }

    public function setTitle($title): void
    {
        $this->$title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text=$text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework()
    {
        return $this->homework;
    }

    public function setHomework($homework): void
    {
        $this->homework=$homework;
    } 
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }

    public function setPrice($price): float
    {
        $this->price=$price;
    } 

}

$paidlesson1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($paidlesson1);
ivashkevich 13.06.2019 в 19:56

Всё ты правильно понял про доступ через публичные методы. Ни на что это не влияет, это именно так и должно работать)

rpash151 22.06.2019 в 14:19
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

    public function getText()
    {
        return $this->text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function setHomework($homework): void
    {
        $this->homework = $homework;
    }

    public function getHomework()
    {
        return $this->homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Позновательные уроки о наследовании',
    'Утро вечера мудренее',99.99);
var_dump($paidLesson    );
ivashkevich 23.06.2019 в 17:49

Для чего сделали поля protected? В коде дочернего класса вы их не используете. А достучаться до них из унаследованных public-методов родительского класса вы можете.

Moskva 29.06.2019 в 15:44
class PaidLesson extends Lesson{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price= $price;
    }

    public function getPrice():string{
        return $this->price;
    }
    public function setPrice(float $price):void{
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90);
var_dump($paidLesson);
ivashkevich 30.06.2019 в 15:04

Отлично

Bizzzon 16.07.2019 в 21:23
class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, int $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function setPrice(float $price)
    {
        $this->price = $price;
    }
    public function getPrice() {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 17.07.2019 в 04:35

Отлично.

    public function getPrice() {
        $this->price = $price;
    }

Скобка, открывающая тело метода, в PHP ставится с новой строки.

Metey 19.07.2019 в 10:34
<?php
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    public $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }
}
$PLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($PLesson);
ivashkevich 20.07.2019 в 14:36
    protected $title;
    protected $text;

Почему protected? Напрямую в дочерних классах не используются?

public function getTitle()

Нужно у геттеров тоже указать тип возвращаемого значения.

public $price;

Тут чего это вообще public стало?

$PLesson

Имена переменных начинаются с маленькой буквы. Всегда.

webdev 19.07.2019 в 16:28

ДЗ

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title,$text,$homework);
        $this->price = $price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }
}

$paidlesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidlesson);
ivashkevich 20.07.2019 в 14:36

Супер

Reechniy 20.07.2019 в 17:54
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}
class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class paidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }
    }
    $paidLesson = new paidLesson('Урок наследования в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 21.07.2019 в 05:22
    protected $title;
    protected $text;
    protected $homework;

Вот это всё должно быть private, так как в дочерних классах нет прямых обращений к этим свойствам.

ivashkevich 21.07.2019 в 05:23

getTitle(): string
Стоит везде указать типы возвращаемых значений.

Blook 31.07.2019 в 22:11
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

    public function getPrice(): float 
    {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 
'Ложитесь спать, утро вечера мудренее', 99.90);
ivashkevich 01.08.2019 в 04:53

Супер!!!

gruimed 04.08.2019 в 13:38
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice() : float
    {
        return $this->price;
    }

    public function setPrice (float $price) : void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Lesson about Inheritance', 'Lol, kek, cheburek', 'Go to sleep', 99.90);
var_dump($paidLesson);
ivashkevich 04.08.2019 в 21:03

Отлично

prognoz 16.08.2019 в 00:59

Почему в сеттерах пишут void?
setTitle($title): void
Что здесь означает void?

ivashkevich 16.08.2019 в 20:29

Это означает, что метод ничего не возвращает (return отсутствует или используется без аргументов)

khuurak 16.08.2019 в 16:11
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent:: __construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$price_PaidLesson = new PaidLesson("Двоичная матрицу", "Дана матрица вида ..", "Расписать двоичную матрицу", 99.90);

echo '<pre>';
var_dump($price_PaidLesson);
echo '</pre>';
ivashkevich 16.08.2019 в 20:30

Отлично

Pro100Bah 02.09.2019 в 11:26
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 02.09.2019 в 18:40
    protected $title;
    protected $text;

Почему protected? Свойства ведь не используются в дочерних классах.

Pro100Bah 03.09.2019 в 16:11
    protected $title;
    protected $text;

1 ВПР. По уроку смотрел, но работает и с приватным модификатором также, а как правильно необходимо было сделать?
2 ВПР. Слетела лицензия на PHPStorm 2018.1; нашел новую скачал и установил PhpStorm 2019.2.1 Build #PS-192.6262.66. Так вот, а новая версия мне показывает все методы в данном домашнем задании(геттеры и сеттеры) с ошибкой: Unused elements: getTitle и так со всеми.
3 ВПР. Забегая немного в перед, это уже с 10-13 урока, при создании классов по уроку дает PHPStorm такое сообщение: 03.09.2019
17:19 Do you want to mark folder as PSR-0 root?
C:/OpenServer 5.3.0/OSPanel/domains/myproject.loc/src
Mark as PSR-0 root
Что мне с ним делать? Мы же вроде по уроку стандарт PSR-4 используем.

ivashkevich 03.09.2019 в 18:56

Если напрямую не используются в дочерних, то всегда private.
Можно посетить как psr-0, чтобы штормик отстал.

Dreft 04.09.2019 в 20:50
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

$test = new PaidLesson('Урок о наследовании в PHP','Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее','99.90');

var_dump($test);
ivashkevich 04.09.2019 в 21:26

Отлично

XXX 23.09.2019 в 14:24
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
}

$paidLesson1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson1);
ivashkevich 23.09.2019 в 14:26

У сеттера тип аргумента потерялся

[email protected] 29.09.2019 в 19:16
<?php

class Post
{
    protected $title;
    protected $text;
    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }
    public function getTitle()
    {
        return $this->title;
    }
    public function setTitle($title): void
    {
        $this->title = $title;
    }
    public function getText()
    {
        return $this->text;
    }
    public function setText($text): void
    {
        $this->text = $text;
    }
}
class Lesson extends Post
{
    protected $homework;
    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }
    public function getHomework(): string
    {
        return $this->homework;
    }
    /**
     * @param string $homework
     */
    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class Paidlesson extends Lesson
{
    protected $price;
    function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    function setPrice(float $price)
    {
        $this->price = $price;
    }
    function getPrice(): string
    {
        return $this->price;
    }
}
?>

Вообще для денег не подходит флоат,но я пока не знаю,чем его заменить)

ivashkevich 30.09.2019 в 00:37

Почему все свойства protected? В дочерних классах ни одно из них не используется.

[email protected] 30.09.2019 в 08:53

Ну,допустим мы не хотим изменения их напрямую,но в будущем мы может будем их использовать в дочерних классах,почему не поставить протектед?

ivashkevich 01.10.2019 в 12:28

Вот когда надо будет, тогда и сделаешь. А по умолчанию всегда ставь private. Иначе непонятно будет, используется ли свойство только в этом классе или где-то ещё.

dliashchenko 08.10.2019 в 14:01
class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice()
    {
        return $this->price;
    }
    public function setPrice($price)
    {
        $this->price = $price;
    }
    public function sayThisText()
    {
        echo 'Заголовок: ' . $this->getTitle() . '<br/>Текст: ' . $this->getText() . '<br/>Домашка: '
            . $this->getHomework() . '<br/>Цена: ' . $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', '99.90');
$paidLesson->sayThisText();
var_dump($paidLesson);
ivashkevich 08.10.2019 в 17:21

Супер!

AleksandrNenashev 09.10.2019 в 23:35

ничего не понял и ничего не получилось(

<?php

class Lesson extends PaidLesson
{
    private $title;
    private $text;
    private $price;

    public function __construct(string $title, string $text, string $price)
    {
        $this->title = $title;
        $this->text = $text;
        $this->price = $price;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

    public function getPrice()
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$Lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($lesson);
ivashkevich 10.10.2019 в 07:48

Зачем здесь повторяются свойства из Lesson? Где типы аргументов? Начинай с курса PHP для начинающих.

Evilinside 11.10.2019 в 15:02
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

    public function getText()
    {
        return $this->text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function setHomework($homework): void
    {
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice( float $price): void
    {
        $this->price = $price;
    }
    public function getPrice()
    {
        return $this->price;
    }
}

$paidLesson_1 = new PaidLesson('Заголовок','Текст','Домашка', 99.90);

var_dump($paidLesson_1);
ivashkevich 11.10.2019 в 21:16
    protected $title;
    protected $text;

Почему protected а не private?

public function setTitle($title)

Почему в конструкторе есть тип аргумента, а здесь нет?

$paidLesson_1

Имена переменных пишутся в camelCase. Не должно быть никаких подчеркиваний.

Evilinside 14.10.2019 в 11:03

Принял, спасибо. Будем исправлять

Evilinside 14.10.2019 в 11:27

Исправил.

<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setText( string $text): void
    {
        $this->text = $text;
    }

    public function getText(): string
    {
        return $this->text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice( float $price): void
    {
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }
}

$paidLesson = new PaidLesson('Заголовок','Текст','Домашка', 99.90);

var_dump($paidLesson);
ivashkevich 14.10.2019 в 11:30

Теперь отлично!

H3licoptero 25.10.2019 в 15:11
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float
    $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$price = new PaidLesson('Урок наследования PHP', 'Бла-бла-бла', 'Кто рано встаёт, тот рано встаёт.', 99.90);
var_dump($price);
echo 'Стоимость обучения в евро: ' . $price->getPrice();
ivashkevich 25.10.2019 в 16:13

И почему цена то string, то float? Непорядок.

H3licoptero 25.10.2019 в 16:28

Упс...недоглядел. Исправил.

ivashkevich 25.10.2019 в 17:48

Теперь отлично

TheTigra 04.11.2019 в 16:49

Домашка:
Еще насколько понимаю, в классе Lesson надо было поменять тип $homework с private на protected?

class PaidLesson extends Lesson {
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price=$price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(string $homework): void
    {
        $this->price = $price;
    }
}
$lesson = new PaidLesson('Урок о наследовании в ООП', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($lesson);
ivashkevich 04.11.2019 в 19:46

Нет. Модификатор доступа private правильный. Мы ведь в дочерних классах не используем это свойство.

Почему цена float, а в конструктор передаёте строку '99.90'?

andreskrip 20.12.2019 в 18:43

В коде урока только заменил private $homework на protected, т.к. идет наследование свойства

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);

Вывод:

object(PaidLesson)[1]
  private 'price' => float 99.9
  protected 'homework' => string 'Ложитесь спать, утро вечера мудренее' (length=67)
  protected 'title' => string 'Урок о наследовании в PHP' (length=43)
  protected 'text' => string 'Лол, кек, чебурек' (length=30)
ivashkevich 21.12.2019 в 20:18

private свойства наследуются! К ним просто нет доступа из методов, определенных в дочерних классах! protected здесь не нужен.

[email protected] 05.01.2020 в 20:28

Fatal error: Class 'Post' not found in D:\OSPanel\domains\localhost\PHP.Zone\OOP\Blog\Lesson.php on line 9
Кто подскажет, что слетело в OpenServer или PHPShtorm
Не видит классы и все....устал бороться уже.

ivashkevich 06.01.2020 в 16:44

Файл с классом подключен через include?

[email protected] 09.01.2020 в 19:40
include "Lesson.php";
$lesson = new Lesson('Заголовок', 'Текст', 'Домашка');
echo 'Название урока: ' . $lesson->getTitle();
ivashkevich 11.01.2020 в 10:54

Домашка была другой

kvakazuabr 06.02.2020 в 23:35
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(): void
    {
        $this->price = $price;
    }
}

$paidLesson = new paidLesson(' Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($paidLesson);

у класса Lesson у свойства $homework prived исправил на protected
ivashkevich 12.02.2020 в 12:18

у класса Lesson у свойства $homework prived исправил на protected

Зачем?

И не prived а private

kvakazuabr 11.03.2020 в 22:46

затем чтобы получить его в классе наследнике

ivashkevich 14.03.2020 в 19:51

В классе-наследнике не происходит обращения к этому свойству.

YuraG 08.02.2020 в 18:55

Выкладываю добавленную часть из домашки!

Class PaidLesson extends Lesson
{
    private $price;

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

}

$lesson = new Lesson('Заголовок', 'Текст', 'Домашка');
var_dump($lesson);

$paidLesson = new PaidLesson(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90
);
echo PHP_EOL;
var_dump($paidLesson);
ivashkevich 12.02.2020 в 12:25
Class PaidLesson extends Lesson

Слово class нужно писать с маленькой буквы.

YuraG 13.02.2020 в 07:34

Учту.
Спасибо за Уроки!

ChelovekAndrey 01.03.2020 в 23:06
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice()
    {
        return $this->price;
    }
    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании PHP', 'Лол, кек, чебурек' , 'Ложитесь спать, утро вечера мудренее' , 99.90);
var_dump($paidLesson);
ivashkevich 05.03.2020 в 03:04

Супер!

Lungren 09.03.2020 в 13:47
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        $this->price = $price;
        parent::__construct($title, $text, $homework);
    }

    public function getPrice():string
    {
        return $this->price;
    }

    public function setPrice(string $price):void
    {
        $this->price = $price;
    }
}

    $paidLesson = new paidLesson('Урок о наследовании в PHP','лол,кек,чебурек','Ложитесь спать, утро вечера мудреннее','99.90');
    var_dump($paidLesson);
ivashkevich 10.03.2020 в 16:37

Здрасьте приехали) А чего это мы цену строкой храним. Я сейчас отвернусь, а вы быстренько на float переделайте =)

Lungren 10.03.2020 в 16:53

OK!

Lungren 10.03.2020 в 17:04
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        $this->price = $price;
        parent::__construct($title, $text, $homework);
    }

    public function getPrice():float
    {
        return $this->price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

    $paidLesson = new paidLesson('Урок о наследовании в PHP','лол,кек,чебурек','Ложитесь спать, утро вечера мудреннее','99.90');
    var_dump($paidLesson);
ivashkevich 10.03.2020 в 17:08
'99.90'

А это что за рудимент?)

Lungren 10.03.2020 в 18:52

Не понял. Хост выдаёт:
Название урока: Заголовок
object(Lesson)#2 (3) { ["homework":"Lesson":private]=> string(14) "Домашка" ["title":protected]=> string(18) "Заголовок" ["text":protected]=> string(10) "Текст" } object(PaidLesson)#1 (4) { ["price":"PaidLesson":private]=> float(99.9) ["homework":"Lesson":private]=> string(69) "Ложитесь спать, утро вечера мудреннее" ["title":protected]=> string(43) "Урок о наследовании в PHP" ["text":protected]=> string(28) "лол,кек,чебурек" }

Lungren 10.03.2020 в 19:53
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework , float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice():float
    {
        return $this->price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

    $paidLesson = new paidLesson('Урок о наследовании в PHP','лол,кек,чебурек','Ложитесь спать, утро вечера мудреннее', 99.90);
    var_dump($paidLesson);

//Разве что без кавычек
ivashkevich 11.03.2020 в 04:51

Ну конечно! Тип float, а передаёте строку. PHP, конечно, преобразует такое, но там где мы можем подставить сразу правильный тип, мы должны это делать.

Lungren 09.03.2020 в 13:48

Только вот с выводом через echo что-то не получилось.

Salexandr 15.03.2020 в 23:23
class PaidLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson1);
ivashkevich 16.03.2020 в 20:01

Почему цена строкой-то? :)

Salexandr 17.03.2020 в 00:09

Потому что не внимательный :)
Конечно, апострофы нужно убрать.

ivashkevich 17.03.2020 в 06:09

Кавычки, разумеется, нужно убрать. А еще что нужно сделать?

Salexandr 17.03.2020 в 09:40

В конструкторе надо тип поменять на float $price и в геттере тип возвращаемого значения :float выставить. О, Боже! Куда я вообще смотрел когда делал домашку?! :-0

ivashkevich 17.03.2020 в 13:43

Верно

Dimitry 01.04.2020 в 16:00
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

public function getHomework(): string
{
    return $this->homework;
}

public function setHomework(string $homework): void
{
    $this->homework = $homework;
}
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price=$price;
    }
    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее','99.90');

var_dump($lesson);

Домашка

ivashkevich 01.04.2020 в 18:09

Почему поля вдруг стали protected?

Dimitry 02.04.2020 в 02:35

Чтобы был доступ к ним из дочерних классов

ivashkevich 02.04.2020 в 05:41

Но в дочерних классах нет прямого обращения к этим свойствам. Они обращаются к ним через public-методы родителей, а так можно. Так что все свойства в вашем примере должны быть private.

Dimitry 02.04.2020 в 05:54
<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

public function getHomework(): string
{
    return $this->homework;
}

public function setHomework(string $homework): void
{
    $this->homework = $homework;
}
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price=$price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее',99.90);

echo "<pre>";
var_dump($lesson);
echo "<pre>";
ivashkevich 02.04.2020 в 07:54

Отлично

leffo 02.04.2020 в 14:18
<?php

/**
 * class Post simple
 */
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        # code...
        $this->title = $title;
        $this->text = $text;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * @param string $text
     */
    public function setText($text)
    {
        $this->text = $text;
    }

}

/**
 * class Lesson потомок поста.
 */
class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    /**
     * @return string
     */
    public function getHomework(): string
    {
        return $this->homework;
    }

    /**
     * @param string $homework
     */
    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLessons extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    /**
     * @return float
     */
    public function getPrice(): float
    {
        return $this->price;
    }

    /**
     * @param float $price
     */
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
?>
<pre>
    <?php
    $plesson = new PaidLessons('Урок о наследовании в PHP', ' Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее.', 99.99);
    var_dump($plesson);
    ?>
</pre>
ivashkevich 02.04.2020 в 15:23

Всё ок, только не указали типы аргументов для сеттеров.

# code...

И вот это не понял что такое

leffo 02.04.2020 в 17:57

Это типа "to do", здесь должен быть размещен твой самый лучший код! :-), забыл удалить.
Насчет строгой типизации - спвсибо, забываю про 7 пхп.

ivashkevich 02.04.2020 в 18:03

Ок) На комментарии можно отвечать (кнопка справа со стрелочкой)

Dmitry.Dudin 06.04.2020 в 21:38
<?php
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title,string $text)
    {
        $this->title=$title;
        $this->text=$text;
    }
    public function getTitle(){
        return $this->title;
    }
    public function setTitle($title):void
    {
        $this->title=$title;
    }
    public function getText()
    {
        return $this->text;
    }
    public function setText($text) :void
    {
        $this->text=$text;
    }
}
class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title,string $text,string $homework){
        parent::__construct($title,$text);
        $this->homework=$homework;
    }
    public function getHomework():string
    {
        return $this->homework;
    }
    public function setHomework(string $homework): void
    {
        $this->homework=$homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title,string $text, string $homework, string $price){
        parent::__construct($title,$text,$homework);
        $this->price=$price;
    }
    public function getPrice():string
    {
        return $this->price;
    }
    public function setPrice(double $price): void
    {
        $this->price=$price;
    }

}

$lesson = new PaidLesson('Урок о наследовании в PHP','Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее',99.90);
var_dump($lesson);

/*
Да, я вкурсе форматирования, обещаю, завтра я поставлю PHPStorm, и заморачиваться с форматированием)

*\

ivashkevich 07.04.2020 в 09:25
    protected $title;
    protected $text;

Должно быть private.

Alexann 08.04.2020 в 15:51
...
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paid_lesson = new PaidLesson('Урок о наследовании PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.9);
var_dump($paid_lesson);
ivashkevich 08.04.2020 в 19:13

Отлично

[email protected] 10.04.2020 в 22:38
class PaidLesson extends Lesson {
  private $price;

  public function __construct(string $title, string $text, string $homework,string $price) {
    parent::__construct($title, $text, $homework);
    $this->price = $price;
  }
  public function getPrice() {
    return $this-> $price;
  }
  public function setPrice(string $price) {
    $this->price = $price;
  }
}

$myLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

var_dump($myLesson);
ivashkevich 11.04.2020 в 21:13

А цена чего строкой? И фигурная скобка, открывающая тело функции, пишется на следующей строке.

Fill 14.04.2020 в 20:41
<?php

//В классе Lesson изменил модификатор доступа у $homework на protected

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(string $price): void
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson); //object(PaidLesson)#2 (4) { ["price":"PaidLesson":private]=> string(5) "99.90" ["homework":protected]=> string(67) "Ложитесь спать, утро вечера мудренее" ["title":protected]=> string(43) "Урок о наследовании в PHP" ["text":protected]=> string(30) "Лол, кек, чебурек" } 
ivashkevich 15.04.2020 в 06:27

В классе Lesson изменил модификатор доступа у $homework на protected

Это еще зачем? Должно оставаться private.

Почему цена строкой? Это же числовое значение.

Fill 15.04.2020 в 06:54

Нам же необходимо наследовать $homework.
Цену нужно float сделать

ivashkevich 15.04.2020 в 11:30

Ну так она наследуется, она просто недоступна для методов этого класса. Но при этом она доступна через публичные методы родительского класса.

Fill 15.04.2020 в 12:51

Спасибо, теперь понял!

[email protected] 14.04.2020 в 23:40

Доброго времени суток, сижу на самоизоляции, кусок кода к Вашему коду:

<?php
class PaidLesson extends Lesson
{
    public $price;

        public function __construct(string $title, string $text, string $homework, $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99,90');
var_dump($lesson);
ivashkevich 15.04.2020 в 11:14

Почему public? И почему строка? И почему поехала первая строка конструктора?

[email protected] 14.04.2020 в 23:43

ещё должен был добавить

    public function setPrice($price):void {
        $this->price = $price;
    }
    public function getPrice(){
        return $this->price;
    }

но я так и не понял, почему этот код должен быть, и почему его писали коллеги по цэху?

ivashkevich 15.04.2020 в 11:16

Где тип аргумента? Почему скобка фигурная на той же строке, что и имя метода? Посмотрите в обязательном порядке урок по функциям из курса PHP для начинающих.

Коллеги писали его потому, что читали внимательно предыдущий урок, и знали, что свойство должно быть private.

ivashkevich 15.04.2020 в 11:17

И оформляйте код перед отправкой комментария (первая кнопка в редакторе).

[email protected] 18.04.2020 в 21:16

Доброго времени суток, вроде всё исправил:
class PaidLesson extends Lesson
{
private $price;

public function __construct(string $title, string $text, string $homework, $price)
{
    parent::__construct($title, $text, $homework);
    $this->price = $price;
}
    public function setPrice(float $price):void 
{
    $this->price = $price;
}
    public function getPrice()
{
    return $this->price;
}

}

$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99,90');
var_dump($lesson);

ivashkevich 19.04.2020 в 15:32

А код почему не оформили опять?

[email protected] 19.04.2020 в 16:03

добрый день, я просто в нотепад++ всё делаю, там видеться всё вот так.

ivashkevich 19.04.2020 в 17:10

Я про комментарий. Перечитайте мои предыдущие сообщения. В редакторе комментариев есть специальная кнопка для оформления.

ivashkevich 19.04.2020 в 17:11

И почему не шторм? Дебаггером умеете пользоваться?

[email protected] 19.04.2020 в 17:23

у меня win 7 x 32. на 64 не перешёл пока.

[email protected] 27.04.2020 в 00:45

попробуй использовать клавишу Tab

[email protected] 27.04.2020 в 00:46

я тоже пишу в Notepad++

[email protected] 27.04.2020 в 00:48

привет, нотепад не так уж и плох. спасибо.

OLEG-M 17.04.2020 в 19:44
class PaidLesson extends Lesson 
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

Еще хотел вывести не через var_dump, пока только так получилось ))

echo $paidLesson->getTitle() . PHP_EOL . $paidLesson->getText() . PHP_EOL . $paidLesson->getHomework() . PHP_EOL . $paidLesson->getPrice();

А как можно сразу все вывести, без отдельных гетеров ??

ivashkevich 18.04.2020 в 05:54

Отлично.

Как вариант - сделать метод toArray(), который будет формировать массив вида ключ-значение. Но в этом методе конечно нужно будет описать весь маппинг. Вариант с var_dump для отладки - самое то!

Timurik 19.04.2020 в 18:55

Вот что у меня получилось:

<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework; //Изменил

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    protected $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$paidLesson = new PaidLesson('Урок о наследовании в PHP','Лол, кек, чебурек','Ложитесь спать, утро вечера мудренее',99.90);
var_dump($paidLesson);
ivashkevich 19.04.2020 в 19:27

Почему все свойства стали protected? К ним ведь нет обращения в дочерних классах.

Timurik 19.04.2020 в 19:39

Я сделал чтобы можно было обращаться при необходимости, хотя в случае необходимости и private на protected не долго изменить)
Я исправил
вот здесь:

class Lesson extends Post
{
    private $homework; 

и тут:

class PaidLesson extends Lesson
{
    private $price;
ivashkevich 19.04.2020 в 19:43

Неправильный подход. Правильнее исходить из того, что нужно сейчас и по-максимуму делать все поля private. А уж если понадобится, то ослаблять доступность.
А в Post почему оставили protected?

Timurik 19.04.2020 в 19:59

тоже исправил:

class Post
{
    private $title;
    private $text;

Понял, большое спасибо, учту на будущее.

studentDev 23.04.2020 в 13:23
<?php
    class Post
    {
        private $title;
        private $text;

        public function __construct(string $title, string $text)
        {
            $this->title = $title;
            $this->text = $text;
        }

        public function getTitle()
        {
            return '</br> <h1>' . $this->title . '</h1>';
        }

        public function setTitle(string $title): void
        {
            $this->title = $title;
        }

        public function getText()
        {
            return '</br>' . $this->text;
        }

        public function setText(string $text): void
        {
            $this->text = $text;
        }
    }

    class Lesson extends Post
    {
        private $homework;

        public function __construct(string $title, string $text, string $homework)
        {
            parent::__construct($title, $text);
            $this->homework = $homework;
        }

        public function getHomework(): string
        {
            return '</br> <b><i>' . $this->homework . '</b></i>';
        }

        public function setHomework(string $homework): void
        {
            $this->homework = $homework;
        }
    }

    class PaidLesson extends Lesson
    {
        private $price;

        public function __construct(string $title, string $text, string $homework, float $price)
        {
            parent::__construct($title, $text, $homework);
            $this->price = $price;
        }

        public function getPrice(): float
        {
            echo $this->price;
        }

        public function setPrice(float $price)
        {
            $this->price = $price;
        }
    }

    $lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.00);
    var_dump($lesson);

RESULT:

object(PaidLesson)#1 (4) {
  ["price":"PaidLesson":private]=>
  float(99)
  ["homework":"Lesson":private]=>
  string(67) "Ложитесь спать, утро вечера мудренее"
  ["title":"Post":private]=>
  string(43) "Урок о наследовании в PHP"
  ["text":"Post":private]=>
  string(30) "Лол, кек, чебурек"
}
ivashkevich 23.04.2020 в 19:15

Почему свойства стали protected?

[email protected] 27.04.2020 в 13:10
<?php
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle():string
    {
        return $this->title;
    }

    public function setTitle($newTitle): void
    {
        $this->title = $newTitle;
    }

    public function getText():string
    {
        return $this->text;
    }

    public function setText($newText): void
    {
        $this->text = $newText;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework():string
    {
        return $this->homework;
    }

    public function setHomework(string $newHomework): void
    {
        $this->homework = $newHomework;
    }
}
class PaidLesson extends Lesson
    {

    private $price;

    public function __construct( string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice():float 
    {
        return $this->price;
    }

    public function setPrice(float $newPrice):void
    {
        $this->price = $newPrice;
    }

}

$paidLesson  = new PaidLesson('Урок о наследование PHP', 'Лол,кек,чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson); 

Изначально код писал на компьютере, но видимо он у меня лаганул и показывал 2 момх комента. Зашёл с телефона и увидел, что кода моего нет.
Пришлось, используя чужой код, воссоздавать свой код с телефона, ибо с телефона форматировать код вообше неудобно.
P.S. мой код действительно так и выглядел, даже имена переменных на свои поменял ($newTitle, $newText, $newHomework, $newPrice)

ivashkevich 27.04.2020 в 20:06
$new_price

Нужно перечитать урок по переменным из курса для начинающих.

$this -> text

Не нужны пробелы слева и справа от этого оператора. Где вы их взяли?

[email protected] 27.04.2020 в 20:41

Урок прочитал(я с других источников пришёл, но здесь я понял, что это рай для мозга), исправил имена переменных
убрал пробелы, по незнанию ставил пробелы, чтобы мне было понятно и приятно, перестал ставить. Придётся переделывать все свои коды :>
Благо, я недавно начал проходить ООП и много кода не создал. Ваши уроки помогают, начал проходить ООП на другом сайте и не понял тему интерфейсов, а здесь понял.

ivashkevich 27.04.2020 в 20:55

Ок, теперь отличная домашка

titelivus 03.05.2020 в 18:33
<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float$price): void
    {
        $this->price = $price;
    }
}

$lesson = new PaidLesson('Урок о наследовании в PHP',
                         'Лол, кек, чебурек',
                         'Ложитесь спать, утро вечера мудренее',
                         99.90);

var_dump($lesson);
ivashkevich 03.05.2020 в 21:04

Отлично

[email protected] 08.05.2020 в 19:05
<?php
class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }
    public function getTitle()
    {
        return $this->title;
    }
    public function setTitle(string $title): void
    {
        $this->title = $title;
    }
    public function getText()
    {
        return $this->text;
    }
    public function setText(string $text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    protected $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }
    public function getHomework(): string
    {
        return $this->homework;
    }
    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$paidLesson1 = new PaidLesson('Урок о наследовании в РНР', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson1);
ivashkevich 08.05.2020 в 20:32
    protected $title;
    protected $text;

Почему свойства стали protected?

[email protected] 10.05.2020 в 12:38

Написала так же, как в примере кода, что получился в ходе урока.

ivashkevich 10.05.2020 в 18:41

Вы правы, в уроке я допустил некоторую неточность. Дополнил урок, начиная со слов: "Обратите внимание, что если у родительского класса есть метод...". Изучите, пожалуйста, это дополнение.

[email protected] 10.05.2020 в 18:44

Хорошо, спасибо)

leoT 12.05.2020 в 16:20

Вопрос, если не указать переменную $price в описании класса, но указать в конструкторе...это ошибка, но почему-то все работает, почему?

class PaidLesson extends Lesson
{
    //private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price= $price;
    }

    public function setPrice(int $price): void
    {
        $this->price=$price;
    }

    public function getPrice(): int {
        return $this->price;
    }

}

$priceLesson = new PaidLesson('Lesson about inheritance', 'LOL, KEK, CHEBUREK','Get Sleep',99.90);
var_dump($priceLesson);
ivashkevich 13.05.2020 в 07:20

Потому что в PHP можно на лету создать свойство класса, будь он не ладен) Но делать так не стоит.

[email protected] 15.05.2020 в 12:41
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }

}
$paidLesson= new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 15.05.2020 в 18:37

Супер!

Sviatoslav 17.05.2020 в 19:29

Мой пример

<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$lesson = new Lesson('Заголовок', 'Текст', 'Домашка');
var_dump($lesson);
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);

Есть вопрос по сеттерах. Для чего мы указываем тип возвращаемого значения void у них? В мануале пишет, что такие функции не должны ничего возвращать. А вот для чего это нам я так и не понял.

ivashkevich 18.05.2020 в 06:10
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');

Последний параметр float

Для чего мы указываем тип возвращаемого значения void у них?

Чтобы было понятно, что от этого метода не стоит ждать возвращаемого значения.

Sviatoslav 18.05.2020 в 19:24
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

Понял свою ошибку. php "скушало" строку потому и не заметил ошибки)

ivashkevich 19.05.2020 в 06:08

Ага, можно юзать директиву strict_types дополнительно

n.yurasheva 18.05.2020 в 00:28
<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 18.05.2020 в 06:11

Идеально

IePyton 26.05.2020 в 16:58
<?php

class Post
{
    protected $title;
    protected $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(): string
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 27.05.2020 в 17:57
    protected $title;
    protected $text;

Почему protected?

IePyton 27.05.2020 в 18:04
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(): string
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 27.05.2020 в 18:10

'99.90'

А почему цена - это строка?)

IePyton 27.05.2020 в 18:13

блин) точно

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(): float
    {
        $this->price = $price;
    }

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 27.05.2020 в 21:07
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90')

А передаёте всё равно строку)

    public function setPrice(): float
    {
        $this->price = $price;
    }

Ошибка

IePyton 01.06.2020 в 13:44
<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
{
    $this->price = $price;
}

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 01.06.2020 в 16:26

В конструкторе исправили, но передаётся туда всё равно строка. PHP конечно умный и всё исправит, но лучше делать это за него и явно.

IePyton 01.06.2020 в 17:15
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }

}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
{
    $this->price = $price;
}

}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);

Мне кажется я понял чего ты добиваешься ))

ivashkevich 01.06.2020 в 20:32

Теперь отлично

Мне кажется я понял чего ты добиваешься ))

Чего?)

[email protected] 05.06.2020 в 16:49

Спасибо за интересное задание: выполнила с удовольствием! Намного понятнее излагаете основные принципы, чем в книжках или других ресурсах.
Вопросик: Я использую св-во price типа string, поскольку решила, что нужно точно создать объект как в примере, однако, если опустить слова 'цена', то можно объявить тип float, поскольку значение 99.90, верно? ). Опустила в начале кода <?php - ведь это отрывок из программы с классами Post и Lesson

/*создаем класс PaidLesson (платный урок), являющийся наследником Leson*/
class PaidLesson extends Lesson 
{
    private $price; //объявляем свойство price (цена)

    /*конструктор*/
    public function __construct(string $title, string $text, string $homework, string $price)
    {
        parent :: __construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): string //геттеры 
    {
        return $this->price;
    }

    public function setPrice(string $price): void //сеттеры
    {
        $this->price = $price;
    }

}
    //создание объекта класса с требуемыми свойствами
    $paidLesson = new PaidLesson(
        'заголовок: Урок о наследовании в PHP', 
        'текст: Лол, кек, чебурек', 
        'домашка: Ложитесь спать, утро вечера мудренее',
        'цена: 99.90'
    );
    var_dump($paidLesson); //вывод объекта через var_dump()

/*object(PaidLesson)[1]
  private 'price' => string 'цена: 99.90' (length=15)
  private 'homework' (Lesson) => string 'домашка: Ложитесь спать, утро вечера мудренее' (length=83)
  private 'title' (Post) => string 'заголовок: Урок о наследовании в PHP' (length=63)
  private 'text' (Post) => string 'текст: Лол, кек, чебурек' (length=42)*/
ivashkevich 06.06.2020 в 08:36

если опустить слова 'цена', то можно объявить тип float, поскольку значение 99.90, верно

Не можно, а нужно. Как и во всех остальных случаях не нужно писать что это такое, просто данные передавайте.

$paidLesson = new PaidLesson(
        'Урок о наследовании в PHP', 
        'Лол, кек, чебурек', 
        'Ложитесь спать, утро вечера мудренее',
        99.90
    );
superbobr 05.06.2020 в 17:02
<?php
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Lesson{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price){
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float {
        return $this->price;
    }

    public function setPrice($price): void {
        $this->price = $price;

    }
}

$lesson1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($lesson1);
ivashkevich 06.06.2020 в 08:37

Отлично. Только скобка, открывающая тело метода, пишется на новой строке.

happyviolence 12.06.2020 в 22:38
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, int $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): int
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$PaidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($PaidLesson);
ivashkevich 13.06.2020 в 09:06

Потеряли 90 центов =(

happyviolence 13.06.2020 в 13:10

блин, точно! тип float, а не int!

ivashkevich 14.06.2020 в 13:24

Ага. Исправлять будем?)

happyviolence 14.06.2020 в 18:30
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$PaidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($PaidLesson);
ivashkevich 15.06.2020 в 20:37

Отлично

[email protected] 25.06.2020 в 23:01

Добрый вечер,

class PaidLesson extends Lesson{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(){
        return $this->price;
    }
    public function  setPrice($price){
        $this->price = $price;
}
}
$object = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее',
'99.90');
var_dump($object);
ivashkevich 26.06.2020 в 09:28

Отлично!

Hellbound 11.07.2020 в 18:01
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice() : float
    {
        return $this->price;
    }

    public function setPrice($price): void
    {
        $this->price = $price;
    }
}

$paidLesson1 = new PaidLesson(
    'Урок о наследовании в PHP',
    'Лол, кек, чебурек',
    'Ложитесь спать, утро вечера мудренее',
    99.90
);

var_dump($paidLesson1);
ivashkevich 12.07.2020 в 06:12
    public function getPrice() : float

Всё отлично, но проблема с форматированием. Делайте отступы и переносы как в уроках. Для этого в шторме можно нажать Ctrl+Alt+L

VitaliyB 26.07.2020 в 20:03
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        {
            parent::__construct($title, $text, $homework);
            $this->price = $price;
        }
    }

    public function getPrice(): string
    {
        return $this->price;
    }

    public function setPrice(): string
    {
        return $this->price;
    }
}
$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 27.07.2020 в 18:46
, '99.90')

Почему строка?

VitaliyB 27.07.2020 в 18:59

Исправил.

ivashkevich 27.07.2020 в 19:11

Не вижу)

VitaliyB 27.07.2020 в 20:10

...

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 29.07.2020 в 17:44

Ок. Если что - комменты можно редактировать.

irina-naletova 02.09.2020 в 17:55
class PaidLesson extends Lesson {
   private $price;

   function __construct(string $title, string $text, string $homework, float $price) {

   parent::__construct($title, $text, $homework);
   $this->price = $price;
   }
   public function setPrice(float $price): void {
   $this->price = $price;
   }
   public function getPrice(): float {
   return $this->price;
   }
}

   $paidLesson = new PaidLesson('Урок о наследовании в PHP',' Лол, кек, чебурек','Ложитесь спать, 
   утро вечера мудренее','99.90');

   var_dump($paidLesson);
ivashkevich 03.09.2020 в 17:50

Почему цена - строка?

Проблема с форматированием. Делайте отступы и переносы как в уроках. Для этого в шторме можно нажать Ctrl+Alt+L

irina-naletova 03.09.2020 в 19:34

Спасибо, исправила, да цена float

Ed8L 20.10.2020 в 18:24
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$lessonAboutExtending = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($lessonAboutExtending);

Кстати почему у меня var_dump в одну строку все выводит, а не как у других с форматированием?

ivashkevich 21.10.2020 в 04:59

По домашке - всё отлично)

[email protected] 08.11.2020 в 15:47
<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson  extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price)
    {
        $this->homework = $price;
    }
}

$PL = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($PL);
ivashkevich 08.11.2020 в 15:51

Почему в конструкторе класса не указан тип для аргумента цены?

[email protected] 09.11.2020 в 00:40

Мои рекомендации: по уроку Наследование в PHP.
Создать папку classes. В ней создать три файла с классами: два класса + один из домашки с названиями:

  • PaidLessonBlog
  • LessonBlog
  • PostBlog
    Создать файл index.php или можете назвать Run.php. Который размещён выше на уровень папки classes, вообщем не в этой папке. И он служит для создания и вызовов методов:
<?php
error_reporting(-1); //Подключили отображение ошибок
require_once 'classes/PostBlog.php'; //Должен быть порядок, так как классы могут не увидеть друг друга.
require_once 'classes/LessonBlog.php';
require_once 'classes/PaidLessonBlog.php';

function debug($data){ //Чтобы было красиво
    echo '<pre>' . print_r($data,1) . '</pre>';
}

/*$lesson = new LessonBlog('Заголовок', 'Текст', 'Домашка');
debug($lesson);*/
$PaidLesson = new PaidLessonBlog('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Домашка','99.90', 'Ложитесь спать, утро вечера мудренее');
debug($PaidLesson);
ivashkevich 09.11.2020 в 19:20

Обосновать можете, почему нужно сделать так?

Для чего везде приписка Blog?

Что даст раскладывание по одноименным файлам без применения автозагрузки?

Вместо кастомной функции debug стоит использовать var_dump с соответствующей конфигурацией.

Почему цена передаётся строкой?

Почему имя переменной PaidLesson с большой буквы?

[email protected] 10.11.2020 в 03:21

1) Каждый класс должен быть в отдельном файле.
2) Blog - так для меня более понятно, что эти классы относятся к Блогу.
3) Сначала, показать такой способ, потом в следующем уроке ещё лучше:

function autoloader1($class) {
    $file = __DIR__ . "/classes/{$class}.php";
    //Проверка: существует ли файл по указанному пути
    if (file_exists($file)) {
        require_once $file;
    }
}
/*2) Для интерфейсов:*/
function autoloader2($class) {
    $file = __DIR__ . "/classes/interfaces/{$class}.php";
    //Проверка: существует ли файл по указанному пути
    if (file_exists($file)) {
        require_once $file;
    }
}
spl_autoload_register('autoloader1');
spl_autoload_register('autoloader2');

А потом можно в следующем уроке показать ещё лучше с Компоузером.
4) Можно и так и так, но с кастомной будет красиво и с отступами.
5) По цене забыл, исправлю, кстати почему цену нельзя строкой передавать, забыл почему?
6) Это исправлю на какой-то из способов:
есть два способа именования переменных:
1) $paid_lesson
2) $paidLesson – первая с маленькой, каждое следующее с большой

ivashkevich 10.11.2020 в 19:21

1) Для чего?
2) Лучше положить их в соответствующий неймспейс
3) Всё будет дальше, не забегайте вперёд. В общем-то, это можно написать ко всем пунктам и на этом закончить)
4) Не поверите, но во встроенной еще и подсветка кода будет
5) Зачем строкой, если на входе ожидается float?
6) 2ой вариант единственно верный, соответствующий PSR

[email protected] 10.11.2020 в 23:06

1) webformyself - курс про ООП, в первой части видео говориться:
Возьмите за привычку располагать один класс в одном файле. И там должно быть только описание класса. А если мы хотим использовать этот класс, то должны его подключить в тех местах, где мы это хотим сделать. Имя файла должно совпадать с именем класса для удобства в дальнейшем. Также имя класса идёт с большой буквы согласно требованиям PSR, но не обязательно. В имя класса могут входить все слова, кроме зарезервированных слов, которые входят в определённый список.
Если есть у Вас альтернатива вышесказанному, "что все классы лучше в одном файле", то аргументируйте ответ, отнесусь с пониманием. Да, нашёл и у Вас ответ на мой вопрос, в уроке про namespace: "В этом уроке мы затронем стандарт PSR-4. В нём говорится о том, что каждый класс должен храниться в отдельном файле и находиться в пространстве имён. Давайте обо всём по порядку."
Остальное - понятно.

ivashkevich 13.11.2020 в 02:25

Ну в общем-то главное чтобы было понимание для чего это делается. А делается это для того чтобы было возможно реализовать автозагрузку. Без раскладывания классов по одноименным файлам этого не добиться.

pixel 16.11.2020 в 16:40
    class PaidLesson extends Lesson
    {
        private $price;

        public function __construct(string $title, string $text,
                                    string $homework, float $price)
        {
            parent::__construct($title, $text, $homework);
            $this->price = $price;
        }

        public function getPrice(): float
        {
            return $this->price;
        }

        public function setPrice(float $price)
        {
            $this->price = $price;
        }
    }

    $title = 'Урок о наследовании в PHP';
    $text = 'Лол, кек, чебурек';
    $homework = 'Ложитесь спать, утро вечера мудренее';
    $price = 99.90;

    $lesson = new PaidLesson($title, $text, $homework, $price);
    var_dump($lesson);
ivashkevich 17.11.2020 в 17:21

Отлично

MikeSiebel 19.11.2020 в 12:26

Добрый день!
В домашке добавил следующее

class PaydLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paydLesson = new PaydLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paydLesson);

Получил:
C:\xampp\htdocs\ws_OOP\3post\index.php:76:
object(PaydLesson)[1]
private 'price' => float 99.9
private 'homework' (Lesson) => string 'Ложитесь спать, утро вечера мудренее' (length=67)
private 'title' (Post) => string 'Урок о наследовании в PHP' (length=43)
private 'text' (Post) => string 'Лол, кек, чебурек' (length=30)

ivashkevich 19.11.2020 в 20:47

Супер!

Larisa 22.11.2020 в 21:50
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
var_dump($paidLesson);
ivashkevich 23.11.2020 в 17:44

А почему в конструктор цену строкой передаете? Это же число

Larisa 23.11.2020 в 21:28
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }
    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);

Поправила, спасибо!

ivashkevich 24.11.2020 в 10:16

Теперь отлично

serega19860511 05.12.2020 в 12:46
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText(string $text): void
    {
        $this->text;
    }

}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework;
    }
}

class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
echo '<pre>';
var_dump($paidLesson);
echo '</pre>';
$lesson = new Lesson('Наследование', 'Наследование-это...', 'Разберитесь самостоятельно!');
echo 'Название урока: '.$lesson->getTitle(). '; Содержание: '.$lesson->getText(). ';<br> 
Ваше дз: '.$lesson->getHomework().'<hr>';

echo 'Название урока: '.$paidLesson->getTitle(). '; Содержание: '.$paidLesson->getText(). ';<br> 
Ваше дз: '.$paidLesson->getHomework().' А стоит всё это:'.$paidLesson->getPrice();
ivashkevich 06.12.2020 в 07:14

Супер!

kan22 25.12.2020 в 18:24
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 26.12.2020 в 21:44

Отлично

Deny 29.01.2021 в 13:24
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    /**
     * @return mixed
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * @param mixed $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson('Урок о наследовании PHP', 'лол, кек, чебурек',
    'Домашка: ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);
ivashkevich 01.02.2021 в 06:16

Всё ок, только phpDoc не корректен. Должно быть float а не mixed.

dimadima 11.02.2021 в 11:47

class PaidLesson extends Lesson
{
private $price;

public function __construct(string $title, string $text, string $homework, float $price)
{
    parent::__construct($title, $text, $homework);
    $this->price = $price;
}
public function setPrice(float $price):void
{
    $this->price = $price;
}
public function getPrice(): float
{
    return $this->price;
}

}
$lesson = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложись спать, утро вечера мудренее', '99.90');
var_dump($lesson);

ivashkevich 14.02.2021 в 15:13

Нужно оформить код в комментарии (в редакторе комментариев самая первая кнопка).
Нажмите на карандашик и поправьте ваш комментарий, пожалуйста. А потом ответьте мне на этот комментарий. После этого проверю вашу домашнюю работу и отвечу на вопросы.

Vladimir96 10.03.2021 в 18:15

Отлично объясняешь, просто сам в шоке что сначала было все непонятно, а потом прочел и все ок.
Спасибо.
Вот ДЗ.

class PaidLesson extends Lessons 
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }
}

$aboutMyPage = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 
'Ложитесь спать, утро вечера мудренее', 99.90);

var_dump($aboutMyPage);
ivashkevich 10.03.2021 в 18:59

Супер!

Egor.Ka 13.03.2021 в 19:59

Я так понял, что родительский класс может быть только один, который самый первый, и все последующие дочерние классы наследуют его параметры, и тоже самое работает при вызове родительского конструктора? Я это к тому, что при создании объекта класса PaidLesson, у меня в геттер homework не возвращалось никаких значений, хотя я наследую свойства и методы родительского класса (Как я думал изначально именно класса Lesson), и мне пришлось добавить в в конструктор класса PaidLesson свойство $homework ,

$this->homework = $homework;

что бы Var_dump его видел, так как при наследовании родительского конструктора его не видно. Я все правильно сделал или нет ?)
Вот сама домашка

<?php
class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}

class PaidLesson extends Post
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text );
        $this->homework = $homework;
        $this->price = $price;

    }
    public function getPrice(float $price)
    {
        return $price->price;
    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$price1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
echo var_dump($price1);
ivashkevich 17.03.2021 в 16:09

Наследоваться надо от Lesson, а не от Post. У Post нет свойства homework.

Egor.Ka 17.03.2021 в 18:51

Спасибо, как то упустил из виду, что он другому классу принадлежит)
Теперь верно?

<?php

class Post
{
    private $title;
    private $text;

    public function __construct(string $title, string $text)
    {
        $this->title = $title;
        $this->text = $text;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title): void
    {
        $this->title = $title;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setText($text): void
    {
        $this->text = $text;
    }
}

class Lesson extends Post
{
    private $homework;

    public function __construct(string $title, string $text, string $homework)
    {
        parent::__construct($title, $text);
        $this->homework = $homework;
    }

    public function getHomework(): string
    {
        return $this->homework;
    }

    public function setHomework(string $homework): void
    {
        $this->homework = $homework;
    }
}
class PaidLesson extends Lesson
{
    private $price;
    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework );
        $this->price = $price;

    }
    public function getPrice(float $price)
    {
        return $price->price;
    }
    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}
$price1 = new PaidLesson('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', '99.90');
echo var_dump($price1);
ivashkevich 20.03.2021 в 20:40

Да, отлично)

Sergey503 01.05.2021 в 17:09
class PaidLesson extends Lesson
{
    private $price;

    public function __construct(string $title, string $text, string $homework, float $price)
    {
        parent::__construct($title, $text, $homework);
        $this->price = $price;
    }

    public function getPrice(): float
    {
        return $this->price;
    }

    public function setPrice(float $price): void
    {
        $this->price = $price;
    }
}

$paidLesson = new PaidLesson ('Урок о наследовании в PHP', 'Лол, кек, чебурек', 'Ложитесь спать, утро вечера мудренее', 99.90);
var_dump($paidLesson);

Цена получается "99.9", вместо того как написано в задание "цена: 99.90".

ivashkevich 01.05.2021 в 17:49

Ну это же тоже самое

Логические задачи с собеседований