
변수를 사용하는 것처럼 객체의 속성에 접근하고 업데이트할 수 있다. 만약에 객체가 변수가 저장되어 있다면, 변수명을 먼저 지정하고 객체 연산자를 사용하여 작업하려는 속성을 지정한다.
속성에 저장된 값에 접근하려면 다음과 같이 한다.
echo $account->balance;이 코드는 계좌 잔고에 대한 값을 페이지에 어떻게 표시하는지 보여준다.
속성에 저장된 값을 업데이트하려면 다음과 같이 한다.
$account->number = 20148896; $account->type = 'Checking'; $account->balance = 1000.00;
예시
<?php class Customer { public string $forename; public string $surname; public string $email; public string $password; } class Account { public int $number; public string $type; public float $balance; } $customer = new Customer(); $account = new Account(); $customer->email = 'ivy@eg.link'; $account->balance = 1000.00; ?> <?php include 'includes/header.php'; ?> <p>Email: <?= $customer->email ?></p> <p>Balance: $<?= $account->balance ?></p> <?php include 'includes/footer.php'; ?>
메서드는 클래스 정의 내부에 작성된 함수다. 메서드를 호출하려면 객체를 보유하고 있는 변수 이름과 객체 연산자, 그리고 메서드 이름을 사용한다.
객체의 메서드 사용하기
예시
<?php class Account { public int $number; public string $type; public float $balance; public function deposit(float $amount): float { $this->balance += $amount; return $this->balance; } public function withdraw(float $amount): float { $this->balance -= $amount; return $this->balance; } } $account = new Account(); $account->balance = 100.00; ?> <?php include 'includes/header.php'; ?> <p>$<?= $account->deposit(50.00) ?></p> <?php include 'includes/footer.php'; ?>
클래스 정의에 __construct()라는 생성자 메서드를 추가했다면, 그 메서드 안의 구문은 클래스를 사용하여 객체가 생성될 때 자동으로 실행된다.
예시
<?php declare(strict_types = 1); class Account { public int $number; public string $type; public float $balance; public function __construct(int $number, string $type, float $balance = 0.00) { $this->number = $number; $this->type = $type; $this->balance = $balance; } public function deposit(float $amount): float { $this->balance += $amount; return $this->balance; } public function withdraw(float $amount): float { $this->balance -= $amount; return $this->balance; } } $checking = new Account(43161176, 'Checking', 32.00); $savings = new Account(20148896, 'Savings', 756.00); ?> <?php include 'includes/header.php'; ?> <h2>Account Balances</h2> <table> <tr> <th>Date</th> <th><?= $checking->type ?></th> <th><?= $savings->type ?></th> </tr> <tr> <td>23 June</td> <td>$<?= $checking->balance ?></td> <td>$<?= $savings->balance ?></td> </tr> <tr> <td>24 June</td> <td>$<?= $checking->deposit(12.00) ?></td> <td>$<?= $savings->withdraw(100.00) ?></td> </tr> <tr> <td>25 June</td> <td><?= $checking->withdraw(5.00) ?></td> <td><?= $savings->deposit(300.00) ?></td> </tr> </table> <?php include 'includes/footer.php'; ?>Account 클래스를 사용하여 객체를 생성하고 $checking, $savings라는 변수에 저장한다. PHP 인터프리터는 __construct 메서드를 클래스에서 찾는다.
결과

출처 - 존 두켓, <백엔드 프로그래밍을 위한 PHP & MySQL>, Jpub, 2022