Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
/**
* CharityBranch 代表「分部」。
* ── static 成員:整個機構唯一的「總帳」
* ── 非 static 成員:各分部自己的「分帳」與操作
*/
class CharityBranch
{
/*** ① 共有的總帳 ─ 所有分部共享 ***/
private static float $mainLedger = 0.0;
/*** ② 各分部私有資料 ***/
private string $name;
private float $subLedger = 0.0;
/** 建構子:建立分部實體 */
public function __construct(string $name)
{
$this->name = $name;
}
/** 捐款:分帳 + 總帳 同步增加(非 static 方法) */
public function donate(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException("捐款金額必須 > 0");
}
$this->subLedger += $amount; // 更新分帳
self::$mainLedger += $amount; // 更新總帳
echo "{$this->name} 獲得捐贈:"
. number_format($amount, 2) . PHP_EOL;
}
/** 拿回捐款:分帳 + 總帳 同步減少(非 static 方法) */
public function withdraw(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException("提款金額必須 > 0");
}
if ($amount > $this->subLedger) {
throw new RuntimeException("分帳餘額不足");
}
$this->subLedger -= $amount;
self::$mainLedger -= $amount;
echo "{$this->name} 退回捐贈:"
. number_format($amount, 2) . PHP_EOL;
}
/** 印出分帳(非 static) */
public function printSubLedger(): void
{
echo "{$this->name} 分帳餘額:"
. number_format($this->subLedger, 2) . PHP_EOL;
}
/** 印出總帳(static) */
public static function printMainLedger(): void
{
echo "★ 總帳餘額:"
. number_format(self::$mainLedger, 2) . PHP_EOL;
}
}
/* === 建立三個分部(多個 instance) === */
$north = new CharityBranch("北區分部");
$central = new CharityBranch("中區分部");
$south = new CharityBranch("南區分部");
/* === 模擬操作 === */
$north->donate(1000); // 捐款給北區
$central->donate( 500); // 捐款給中區
$south->donate(1500); // 捐款給南區
$north->withdraw(200); // 北區捐款人拿回 200
/* === 報表列印 === */
$north->printSubLedger();
$central->printSubLedger();
$south->printSubLedger();
CharityBranch::printMainLedger(); // 注意:呼叫 static 方法用 ::