類別是 PHP 中組織程式碼的單位,通常代表某個事物、服務或流程的實例。透過static和self關鍵字,屬性和方法可以參照類別本身而存在,供所有實例(或不需要任何實例)取用。
<?php
class Book
{
static $genre = 'Adventure';
static function getGenre()
{
return self::$genre;
}
}
// Usage
$genre = Book::$genre;
$genre = Book::getGenre();
靜態類別方法只能呼叫自己所屬類別中的其他靜態類別屬性或類別方法。
<?php
class Book
{
$name = 'Treasure Island';
static function getName()
{
// This static method cannot access the instance variable
return $this->name;
}
}