クラスは、PHPでコードを整理するための単位で、何らかのもの・サービス・手順のインスタンスを表すことがよくあります。staticとselfというキーワードを使うと、プロパティやメソッドを、すべてのインスタンス(あるいはインスタンスが1つもない場合)を対象として、クラスに紐づけて存在させることができます。
<?php
class Book
{
static $genre = 'Adventure';
static function getGenre()
{
return self::$genre;
}
}
// Usage
$genre = Book::$genre;
$genre = Book::getGenre();
staticなクラスメソッドは、自分自身のクラスにある他のstaticなプロパティやクラスメソッドしか呼び出せません。
<?php
class Book
{
$name = 'Treasure Island';
static function getName()
{
// This static method cannot access the instance variable
return $this->name;
}
}