1.PHP 객체 지향 프로그래밍
PHP의 객체 지향 프로그래밍(OOP)은 코드의 재사용성과 유지보수성을 향상시키기 위한 프로그래밍 패러다임으로, OOP의 주요 개념과 예제는 다음과 같습니다.
2. 클래스
클래스는 객체의 틀(청사진)으로 속성과 메서드를 정의합니다.
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function displayInfo() {
return "차량의 모델: $this->model, 색상: $this->color";
}
}
3.객체(Object)
클래스를 기반으로 생성된 실체입니다.
$myCar = new Car("빨간색", "소나타");
echo $myCar->displayInfo(); // 출력: 차량 모델: 소나타, 색상: 빨간색
4. 상속(Inheritance)
클래스가 다른 클래스의 속성과 메서드를 물려받는 것을 말합니다.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function displayInfo() {
return "차량의 모델: $this->model, 색상: $this->color";
}
}
class ElectricCar extends Car {
public $batteryCapacity;
public function __construct($color, $model, $batteryCapacity) {
parent:: __construct($color, $model);
$this->batteryCapacity = $batteryCapacity;
}
public function displayInfo() {
return parent::displayInfo() . ", 배터리의 용량: $this->batteryCapacity k\h";
}
}
$myElectricCar = new ElectricCar("blue", "Tesla", 200);
echo $myElectricCar ->displayInfo();
?>
5.다형성(Polymorphism)
같은 인터페이스를 사용해 여러 데이터 타입을 처리할 수 있습니다.
<?
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function displayInfo() {
return "차량의 모델: $this->model, 색상: $this->color";
}
}
$myCar = new Car("Red", "Benz");
function printCarInfo(Car $car) {
echo $car->displayInfo();
}
printCarInfo($myCar);
?>
6.캡슐화(Encapsulation)
객체의 속성을 보호하고, 외부에서 직접 접근하지 못하도록 설정하는 접근 제어자를 사용할 수 있습니다.
<?
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$person = new Person();
$person->setName("James");
echo $person->getName(); // result: James
?>
GitHub - Koras02/php-tutorial
Contribute to Koras02/php-tutorial development by creating an account on GitHub.
github.com
LIST
'Back-End > PHP' 카테고리의 다른 글
[PHP] 8장 세션과 쿠키 (0) | 2025.02.26 |
---|---|
[PHP] 7장 파일 입출력 (0) | 2025.02.24 |
[PHP] 5장 PHP 함수와 클래스 (0) | 2025.02.16 |
[PHP] 4장 배열(Array)과 문자열(String) (0) | 2025.02.15 |
[PHP] 3장 PHP의 연산자, 조건문과 반복문 (0) | 2025.02.12 |