/
osipenkoVlada228
/
1.8
Обзор
Документация
Войти
/
osipenkoVlada228
/
1.8
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
oop_lab.php
707 строк
17 KB
Vlada Osipenko
first_commit
22 май 2026, 20:00
22 май 2026, 20:00
49c0262
Код
Авторство
О чём код?
<?php echo "<h1>Шаг 1: Наследование</h1>"; // Базовый класс Animal class Animal { public $name; public $age; public function describe() { print("Это {$this->name}, ему {$this->age} лет.<br>"); } } // Производный класс Dog class Dog extends Animal { public function bark() { print("{$this->name} говорит: Гав-гав!<br>"); } } // Производный класс Cat class Cat extends Animal { public function meow() { print("{$this->name} говорит: Мяу-мяу!<br>"); } } // Демонстрация наследования $dog = new Dog(); $dog->name = 'Бобик'; $dog->age = 3; $dog->describe(); $dog->bark(); $cat = new Cat(); $cat->name = 'Мурка'; $cat->age = 2; $cat->describe(); $cat->meow(); echo "<hr><h1>Шаг 2: Полиморфизм</h1>"; // Базовый класс Animal с методом makeSound() class AnimalPoly { public $name; public $age; public function describe() { print("Это {$this->name}, ему {$this->age} лет.<br>"); } public function makeSound() { print("{$this->name} издаёт звук.<br>"); } } // Производный класс Dog class DogPoly extends AnimalPoly { public function makeSound() { print("{$this->name} говорит: Гав-гав!<br>"); } } // Производный класс Cat class CatPoly extends AnimalPoly { public function makeSound() { print("{$this->name} говорит: Мяу-мяу!<br>"); } } // Создаем массив животных $animals = []; $dogPoly = new DogPoly(); $dogPoly->name = 'Бобик'; $dogPoly->age = 3; $animals[] = $dogPoly; $catPoly = new CatPoly(); $catPoly->name = 'Мурка'; $catPoly->age = 2; $animals[] = $catPoly; // Проходим по массиву и вызываем makeSound() foreach ($animals as $animal) { $animal->describe(); $animal->makeSound(); } echo "<hr><h1>Шаг 3: Инкапсуляция</h1>"; // Базовый класс Animal с приватными свойствами class AnimalEncap { private $name; private $age; public function describe() { print("Это {$this->getName()}, ему {$this->getAge()} лет.<br>"); } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getAge() { return $this->age; } public function setAge($age) { if($age >= 0) { $this->age = $age; } else { print('Возраст не может быть отрицательным.<br>'); } } public function makeSound() { print("{$this->getName()} издаёт звук.<br>"); } } // Производный класс Dog class DogEncap extends AnimalEncap { public function makeSound() { print("{$this->getName()} говорит: Гав-гав!<br>"); } } // Производный класс Cat class CatEncap extends AnimalEncap { public function makeSound() { print("{$this->getName()} говорит: Мяу-мяу!<br>"); } } // Правильная установка через методы-сеттеры $dogEncap = new DogEncap(); $dogEncap->setName('Бобик'); $dogEncap->setAge(3); $dogEncap->describe(); $dogEncap->makeSound(); $catEncap = new CatEncap(); $catEncap->setName('Мурка'); $catEncap->setAge(2); $catEncap->describe(); $catEncap->makeSound(); echo "<hr><h1>Шаг 4: Интерфейсы</h1>"; // Интерфейс Actions interface Actions { public function run(); public function sleep(); } // Класс Dog, реализующий интерфейс Actions class DogInterface extends AnimalEncap implements Actions { public function makeSound() { print("{$this->getName()} говорит: Гав-гав!<br>"); } public function run() { print("{$this->getName()} бежит.<br>"); } public function sleep() { print("{$this->getName()} спит.<br>"); } } // Класс Cat, реализующий интерфейс Actions class CatInterface extends AnimalEncap implements Actions { public function makeSound() { print("{$this->getName()} говорит: Мяу-мяу!<br>"); } public function run() { print("{$this->getName()} крадётся.<br>"); } public function sleep() { print("{$this->getName()} спит.<br>"); } } // Создаем объекты $dogInt = new DogInterface(); $dogInt->setName('Бобик'); $catInt = new CatInterface(); $catInt->setName('Мурка'); // Массив объектов $animalsInt = [$dogInt, $catInt]; // Вызываем методы интерфейса foreach ($animalsInt as $animal) { $animal->run(); $animal->sleep(); } echo "<hr><h1>Шаг 5: Абстрактные классы</h1>"; // Абстрактный класс Animal abstract class AnimalAbstract { private $name; private $age; public function describe() { print("Это {$this->getName()}, ему {$this->getAge()} лет.<br>"); } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getAge() { return $this->age; } public function setAge($age) { if($age >= 0) { $this->age = $age; } else { print('Возраст не может быть отрицательным.<br>'); } } // Абстрактный метод abstract public function makeSound(); } // Класс Dog class DogAbstract extends AnimalAbstract implements Actions { public function makeSound() { print("{$this->getName()} говорит: Гав-гав!<br>"); } public function run() { print("{$this->getName()} бежит.<br>"); } public function sleep() { print("{$this->getName()} спит.<br>"); } } // Класс Cat class CatAbstract extends AnimalAbstract implements Actions { public function makeSound() { print("{$this->getName()} говорит: Мяу-мяу!<br>"); } public function run() { print("{$this->getName()} крадётся.<br>"); } public function sleep() { print("{$this->getName()} спит.<br>"); } } // Правильное создание объектов $dogAbs = new DogAbstract(); $dogAbs->setName('Бобик'); $dogAbs->makeSound(); $catAbs = new CatAbstract(); $catAbs->setName('Мурка'); $catAbs->makeSound(); echo "<hr><h1>Самостоятельная работа 1: Наследование</h1>"; echo "<h2>Задание 1: Иерархия транспортных средств</h2>"; class Vehicle { public $make; public $model; public $year; public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } public function getInfo() { return "{$this->year} {$this->make} {$this->model}"; } } class Car extends Vehicle { public $doors; public function __construct($make, $model, $year, $doors) { parent::__construct($make, $model, $year); $this->doors = $doors; } public function getInfo() { return parent::getInfo() . " (дверей: {$this->doors})"; } } class Bike extends Vehicle { public $type; public function __construct($make, $model, $year, $type) { parent::__construct($make, $model, $year); $this->type = $type; } public function getInfo() { return parent::getInfo() . " (тип: {$this->type})"; } } class Truck extends Vehicle { public $loadCapacity; public function __construct($make, $model, $year, $loadCapacity) { parent::__construct($make, $model, $year); $this->loadCapacity = $loadCapacity; } public function getInfo() { return parent::getInfo() . " (грузоподъёмность: {$this->loadCapacity} кг)"; } } $car = new Car('Toyota', 'Camry', 2020, 4); echo $car->getInfo() . "<br>"; $bike = new Bike('Giant', 'Escape', 2021, 'Горный'); echo $bike->getInfo() . "<br>"; $truck = new Truck('Volvo', 'FH16', 2019, 20000); echo $truck->getInfo() . "<br>"; echo "<h2>Задание 2: Система сотрудников</h2>"; class Employee { protected $name; protected $salary; public function __construct($name, $salary) { $this->name = $name; $this->salary = $salary; } public function getInfo() { return "{$this->name} с зарплатой {$this->salary}"; } } class Manager extends Employee { private $teamSize; public function __construct($name, $salary, $teamSize) { parent::__construct($name, $salary); $this->teamSize = $teamSize; } public function manageTeam() { print("{$this->name} управляет командой из {$this->teamSize} человек.<br>"); } } class Developer extends Employee { private $programmingLanguage; public function __construct($name, $salary, $programmingLanguage) { parent::__construct($name, $salary); $this->programmingLanguage = $programmingLanguage; } public function writeCode() { print("{$this->name} пишет код на {$this->programmingLanguage}.<br>"); } } class Designer extends Employee { private $designTool; public function __construct($name, $salary, $designTool) { parent::__construct($name, $salary); $this->designTool = $designTool; } public function createDesign() { print("{$this->name} создаёт дизайн в {$this->designTool}.<br>"); } } $manager = new Manager('Иван Петров', 150000, 5); echo $manager->getInfo() . "<br>"; $manager->manageTeam(); $developer = new Developer('Анна Сидорова', 120000, 'PHP'); echo $developer->getInfo() . "<br>"; $developer->writeCode(); $designer = new Designer('Ольга Козлова', 100000, 'Figma'); echo $designer->getInfo() . "<br>"; $designer->createDesign(); echo "<hr><h1>Самостоятельная работа 2: Инкапсуляция</h1>"; echo "<h2>Задание 1: Банковский счёт</h2>"; class BankAccount { private $accountNumber; private $balance; public function __construct($accountNumber, $balance = 0) { $this->accountNumber = $accountNumber; $this->balance = $balance; } public function deposit($amount) { if($amount > 0) { $this->balance += $amount; print("Внесено: {$amount}.<br>"); } } public function withdraw($amount) { if($amount > 0 && $amount <= $this->balance) { $this->balance -= $amount; print("Снято: {$amount}.<br>"); } else { print("Недостаточно средств или неверная сумма.<br>"); } } public function getBalance() { return $this->balance; } public function getAccountNumber() { return $this->accountNumber; } } $account = new BankAccount('1234567890', 1000); echo "Счёт {$account->getAccountNumber()}, баланс: {$account->getBalance()}<br>"; $account->deposit(500); echo "Баланс после пополнения: {$account->getBalance()}<br>"; $account->withdraw(300); echo "Баланс после снятия: {$account->getBalance()}<br>"; echo "<h2>Задание 4: Счётчик</h2>"; class Counter { private $count = 0; public function increment() { $this->count++; } public function decrement() { if($this->count > 0) { $this->count--; } } public function getCount() { return $this->count; } } $counter = new Counter(); $counter->increment(); $counter->increment(); $counter->increment(); echo "Счётчик: {$counter->getCount()}<br>"; $counter->decrement(); echo "Счётчик после уменьшения: {$counter->getCount()}<br>"; echo "<hr><h1>Самостоятельная работа 3: Полиморфизм</h1>"; echo "<h2>Задание 1: Уведомления</h2>"; interface Notifier { public function send($message); } class EmailNotifier implements Notifier { public function send($message) { print("Отправка email: {$message}<br>"); } } class SMSNotifier implements Notifier { public function send($message) { print("Отправка SMS: {$message}<br>"); } } class PushNotifier implements Notifier { public function send($message) { print("Отправка Push-уведомления: {$message}<br>"); } } $notifiers = [ new EmailNotifier(), new SMSNotifier(), new PushNotifier() ]; foreach ($notifiers as $notifier) { $notifier->send('Привет! Это тестовое сообщение.'); } echo "<h2>Задание 2: Оплата</h2>"; class Payment { protected $amount; public function __construct($amount) { $this->amount = $amount; } public function process() { print("Обработка платежа на сумму {$this->amount}<br>"); } } class CreditCardPayment extends Payment { private $cardNumber; public function __construct($amount, $cardNumber) { parent::__construct($amount); $this->cardNumber = $cardNumber; } public function process() { print("Оплата картой ****{$this->cardNumber} на сумму {$this->amount}<br>"); } } class PayPalPayment extends Payment { private $email; public function __construct($amount, $email) { parent::__construct($amount); $this->email = $email; } public function process() { print("Оплата через PayPal ({$this->email}) на сумму {$this->amount}<br>"); } } class BankTransferPayment extends Payment { private $bankAccount; public function __construct($amount, $bankAccount) { parent::__construct($amount); $this->bankAccount = $bankAccount; } public function process() { print("Банковский перевод на счёт {$this->bankAccount} на сумму {$this->amount}<br>"); } } $payments = [ new CreditCardPayment(1000, '1234'), new PayPalPayment(2500, 'user@example.com'), new BankTransferPayment(5000, '9876543210') ]; foreach ($payments as $payment) { $payment->process(); } echo "<hr><h1>Самостоятельная работа 4: Traits</h1>"; echo "<h2>Задание 1: Логирование действий</h2>"; trait Logger { public function log($message) { print("Лог: {$message}<br>"); } } class UserWithLogger { use Logger; public function createUser($name) { $this->log("Пользователь {$name} создан."); } } class Order { use Logger; public function createOrder($id) { $this->log("Заказ #{$id} создан."); } } class Product { use Logger; public function addProduct($name) { $this->log("Товар '{$name}' добавлен."); } } $user = new UserWithLogger(); $user->createUser('Алексей'); $order = new Order(); $order->createOrder(101); $product = new Product(); $product->addProduct('Ноутбук'); echo "<h2>Задание 2: Временные метки</h2>"; trait Timestampable { protected $createdAt; protected $updatedAt; public function setCreatedAt() { $this->createdAt = date('Y-m-d H:i:s'); } public function setUpdatedAt() { $this->updatedAt = date('Y-m-d H:i:s'); } public function getCreatedAt() { return $this->createdAt; } public function getUpdatedAt() { return $this->updatedAt; } } class Post { use Timestampable; private $title; public function __construct($title) { $this->title = $title; $this->setCreatedAt(); $this->setUpdatedAt(); } public function getTitle() { return $this->title; } } $post = new Post('Моя первая статья'); echo "Заголовок: {$post->getTitle()}<br>"; echo "Создано: {$post->getCreatedAt()}<br>"; echo "Обновлено: {$post->getUpdatedAt()}<br>"; echo "<h2>Задание 5: Авторизация пользователей</h2>"; trait Authenticatable { protected $isLoggedIn = false; protected $username; public function login($username, $password) { // Простая имитация авторизации if(!empty($username) && !empty($password)) { $this->isLoggedIn = true; $this->username = $username; print("Пользователь {$username} вошёл в систему.<br>"); } } public function logout() { $this->isLoggedIn = false; print("Пользователь {$this->username} вышел из системы.<br>"); $this->username = null; } public function isLoggedIn() { return $this->isLoggedIn; } } class AuthUser { use Authenticatable; } $authUser = new AuthUser(); $authUser->login('student', 'password123'); echo "Авторизован: " . ($authUser->isLoggedIn() ? 'Да' : 'Нет') . "<br>"; $authUser->logout(); echo "Авторизован: " . ($authUser->isLoggedIn() ? 'Да' : 'Нет') . "<br>"; echo "<hr><h1>Все задания выполнены успешно!</h1>";