PHP: A bank account

Encapsulation in action: the class decides whether a change is allowed.

What to build

A program with a BankAccount class that runs commands.

Requirements

  • Write a class BankAccount with a private balance that starts at 0.
  • Read lines until the input ends. deposit N adds N; withdraw N takes N out; balance prints Balance: B.
  • If N is not above 0, print Invalid amount. If a withdrawal is more than the balance, print Insufficient funds and change nothing.

Input

Any number of command lines.

Output

One line for each balance request and each refused command.

Constraints

At most 100 lines; amounts between -1000 and 100000; the balance stays below 1000000.

Example

Input:

deposit 100
withdraw 30
balance

Output:

Balance: 70

Why it works

The class owns the balance, so the rules cannot be bypassed from the outside.

Examples

Example 1 · Input
deposit 100
withdraw 30
balance
Expected output
Balance: 70
Example 2 · Input
withdraw 5
balance
Expected output
Insufficient funds
Balance: 0

Hints

Hint 1

Make the balance private and check the rules inside deposit() and withdraw().

Hint 2

Let withdraw() return false when the balance is too small, and print the message outside the class.

Solution

Show one correct solution (try it yourself first)
<?php
class BankAccount
{
    private int $balance = 0;

    public function deposit(int $amount): void
    {
        $this->balance += $amount;
    }

    public function withdraw(int $amount): bool
    {
        if ($amount > $this->balance) {
            return false;
        }
        $this->balance -= $amount;
        return true;
    }

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

$account = new BankAccount();
while (($line = fgets(STDIN)) !== false) {
    $parts = explode(" ", trim($line));
    $cmd = $parts[0];
    $amount = (int) ($parts[1] ?? 0);
    if ($cmd === "balance") {
        echo "Balance: ", $account->getBalance(), "\n";
    } elseif ($cmd === "deposit" || $cmd === "withdraw") {
        if ($amount <= 0) {
            echo "Invalid amount\n";
        } elseif ($cmd === "deposit") {
            $account->deposit($amount);
        } elseif (!$account->withdraw($amount)) {
            echo "Insufficient funds\n";
        }
    }
}

▶ Open this solution in the compiler

Lesson: Classes and objects →