首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 5 類別屬性與方法完整指南:封裝、可見性、$this、型別提示

     編輯:PHP 相關知識

類別基本結構

name = $name;
        $this->age = $age;
        $this->id = $id;
    }

    // 方法
    public function getName(): string {
        return $this->name;
    }

    protected function setAge(int $age): void {
        if ($age > 0) $this->age = $age;
    }

    private function generateId(): string {
        return uniqid('uid_');
    }
}

可見性關鍵字

關鍵字類別內部子類別外部
public✓✓✓
protected✓✓✗
private✓✗✗

$this 偽變數

  • 僅在物件內容(非靜態方法)中可用。
  • 指向當前物件實例。
  • 存取屬性:$this->property
  • 呼叫方法:$this->method()
  • 靜態方法中不可用,改用 self::、static::、ClassName::。

封裝實作:Getter/Setter

balance;
    }

    public function deposit(float $amount): bool {
        if ($amount <= 0) return false;
        $this->balance += $amount;
        return true;
    }

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

$acc = new BankAccount();
$acc->deposit(1000);
$acc->withdraw(200);
echo $acc->getBalance(); // 800

方法參數與型別提示(PHP 7.0+)

log('processing');
    }
}

屬性初始值限制

  • 可為:標量(int/float/string/bool)、null、array(常數陣列)、物件(PHP 8.1+ new Class())。
  • 不可為:運算式結果、函數呼叫、變數。

物件屬性存取

name;        // 讀取 public 屬性
$p->name = 'Bob';     // 寫入 public 屬性

// 透過方法存取 protected/private
$p->setAge(30);       // 呼叫 protected 方法(若在子類或同類內)
echo $p->getName();   // 呼叫 public 方法

結語

PHP 5+ 完整支援物件導向三大特性:封裝(可見性)、繼承、多型。善用 private 隱藏內部狀態、protected 開放子類擴充、public 定義介面,配合型別提示與嚴格模式,能建構健壯可維護的類別體系。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved