Web Programming/----- PHP -----

[PHP] 객체지향 프로그래밍(OOP)

형수's 2024. 12. 13. 15:24
반응형

 

객체지향 프로그래밍(OOP)은 복잡한 소프트웨어를 더 쉽게 설계하고 관리할 수 있게 해주는 프로그래밍 패러다임입니다. 실제 세계의 개념을 모델링하여 코드를 구조화하는 방식으로, 다음과 같은 주요 개념을 포함합니다:

## 객체와 클래스

- **객체**: 실제 세계의 물건이나 개념을 표현한 것입니다. 예를 들어, '자동차'라는 객체가 있을 수 있습니다.
- **클래스**: 객체를 만들기 위한 '설계도'입니다. '자동차' 클래스는 모든 자동차 객체의 공통적인 특성과 기능을 정의합니다.

// 클래스
class Car {
    public $brand;
    public $color;

    public function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }

    public function getInfo() {
        return "This is a {$this->color} {$this->brand}.";
    }
}

// 인스턴스(객체) 생성
$myCar = new Car("Toyota", "red");
echo $myCar->getInfo(); // 출력: This is a red Toyota.



## 주요 특성

1. **캡슐화**
   - 데이터(속성)와 그 데이터를 처리하는 메서드를 하나의 단위로 묶는 것입니다.

class BankAccount {
    private $balance = 0;

    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
        }
    }

    public function getBalance() {
        return $this->balance;
    }
}

$account = new BankAccount();
$account->deposit(100);
echo $account->getBalance(); // 출력: 100



2. **상속**
   - 기존 클래스의 특성을 새로운 클래스가 물려받는 것입니다.
   - 예: 'ElectricCat' 클래스는 'Car' 클래스의 특성을 상속받아 기본 기능을 유지하면서 추가 기능을 구현합니다.

class ElectricCar extends Car {
    private $batteryLevel;

    public function __construct($brand, $color, $batteryLevel) {
        parent::__construct($brand, $color);
        $this->batteryLevel = $batteryLevel;
    }

    public function getBatteryInfo() {
        return "Battery level: {$this->batteryLevel}%";
    }
}

$myElectricCar = new ElectricCar("Tesla", "blue", 80);
echo $myElectricCar->getInfo(); // 출력: This is a blue Tesla.
echo $myElectricCar->getBatteryInfo(); // 출력: Battery level: 80%



3. **다형성**
   - 같은 이름의 메소드가 다른 클래스에서 다르게 동작할 수 있는 능력입니다.
   - 예: 'move' 메소드가 'Car'와 'Boat' 클래스에서 각각 다르게 구현될 수 있습니다.

interface Vehicle {
    public function move();
}

class Car implements Vehicle {
    public function move() {
        return "The car is driving on the road.";
    }
}

class Boat implements Vehicle {
    public function move() {
        return "The boat is sailing on the water.";
    }
}

function transport(Vehicle $vehicle) {
    echo $vehicle->move();
}

$car = new Car();
$boat = new Boat();

transport($car);  // 출력: The car is driving on the road.
transport($boat); // 출력: The boat is sailing on the water.



4. **추상화**
   - 복잡한 시스템에서 핵심적인 개념이나 기능을 간추려내는 것입니다.

abstract class Shape {
    abstract public function calculateArea();
}

class Circle extends Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * $this->radius * $this->radius;
    }
}

class Square extends Shape {
    private $side;

    public function __construct($side) {
        $this->side = $side;
    }

    public function calculateArea() {
        return $this->side * $this->side;
    }
}

$circle = new Circle(5);
$square = new Square(4);

echo $circle->calculateArea(); // 출력: 약 78.54
echo $square->calculateArea(); // 출력: 16



## OOP의 장점

- **코드 재사용**: 상속을 통해 기존 코드를 쉽게 재사용할 수 있습니다.
- **유지보수 용이성**: 객체 단위로 코드가 모듈화 되어 있어 수정이 쉽습니다.
- **확장성**: 새로운 클래스를 추가하거나 기존 클래스를 수정하여 기능을 쉽게 확장할 수 있습니다.

객체지향 프로그래밍은 이러한 개념들을 활용하여 복잡한 소프트웨어 시스템을 더 체계적이고 효율적으로 구현할 수 있게 해 줍니다. 실제 세계의 개념을 프로그래밍에 적용함으로써, 개발자들은 더 직관적이고 관리하기 쉬운 코드를 작성할 수 있습니다.

반응형