<?php
class Calculator
{
// 屬性 (可視性: public/protected/private)
public $lastResult = 0;
protected $history = [];
private $precision = 2;
// 建構子
public function __construct(int $precision = 2)
{
$this->precision = $precision;
}
// 公開方法
public function add(float $a, float $b): float
{
$result = $a + $b;
$this->record($a, $b, '+', $result);
return $this->lastResult = round($result, $this->precision);
}
public function subtract(float $a, float $b): float
{
$result = $a - $b;
$this->record($a, $b, '-', $result);
return $this->lastResult = round($result, $this->precision);
}
public function multiply(float $a, float $b): float
{
$result = $a * $b;
$this->record($a, $b, '*', $result);
return $this->lastResult = round($result, $this->precision);
}
// 受保護方法 (繼承類可用)
protected function record(float $a, float $b, string $op, float $result): void
{
$this->history[] = "$a $op $b = $result";
}
// 公開存取器
public function getHistory(): array
{
return $this->history;
}
public function getLastResult(): float
{
return $this->lastResult;
}
}
// 實例化與使用
$calc = new Calculator(3); // 精度 3 位小數
echo $calc->add(1.234, 2.345); // 3.579
echo $calc->subtract(10, 3.14159); // 6.858
echo $calc->multiply(2.5, 4); // 10
print_r($calc->getHistory());
/*
Array
(
[0] => 1.234 + 2.345 = 3.579
[1] => 10 - 3.14159 = 6.858
[2] => 2.5 * 4 = 10
)
*/
?>
| 修飾詞 | 類別內部 | 繼承類別 | 外部程式碼 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
<?php
class Base
{
public static $name = 'Base';
public static function who() {
echo __CLASS__ . "\n";
}
public static function test() {
self::who(); // 編譯期綁定: Base
static::who(); // 運行期綁定: 實際調用類
}
}
class Derived extends Base
{
public static $name = 'Derived';
public static function who() {
echo __CLASS__ . "\n";
}
}
Derived::test();
// 輸出:
// Base (self::)
// Derived (static::)
?>
<?php
class Entity
{
public $id;
public $data;
public function __clone()
{
// 深層複製相關物件
$this->data = clone $this->data;
$this->id = 0; // 重置 ID
}
}
$obj1 = new Entity();
$obj1->id = 1;
$obj1->data = new stdClass();
$obj2 = clone $obj1; // 觸發 __clone()
$obj2->id = 2;
// 比較
$obj1 == $obj2; // true (屬性值相同)
$obj1 === $obj2; // false (非同一實例)
?>
<?php
// composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
// 執行 composer dump-autoload 後
require 'vendor/autoload.php';
// 即可直接使用
use App\Services\Calculator;
$calc = new Calculator();
?>
private,透過 getter/setter 控制存取readonly 屬性 (PHP 8.1+)掌握類別聲明與使用,是 PHP 物件導向程式設計的基石。