プログラムの処理をまとめたひな形
//class名の先頭は大文字 class S1Class { //property public $name; //constructor public function __construct($name){ $this->name = $name; } //method public function myEcho(){ echo "Hello" . $this->name . ""; } } $s1Ins = new S1Class("aaa"); echo $s1Ins->name . ""; $s2Ins = new S1Class("bbb"); $s2Ins->myEcho();
個々のインスタンスがもつデータ(プロパティ)ではなく、クラスがもつデータをクラスプロパティといいます。 クラスプロパティは「static」を用いて定義します。 クラスプロパティにアクセスする場合は「クラス名::$クラスプロパティ名」 class Menu { public static $count = 4; public function __construct($name, $price, $image) { $this->name = $name; $this->price = $price; $this->image = $image; } echo Menu::$count
クラス内でクラスプロパティにアクセスする際は「self」という特殊な変数を用います。 selfは、クラスの中で使うとそのクラス自身のことを指し示し、「self::$クラスプロパティ名」 個々のインスタンスのデータに関係ない処理を行いたい時には「クラスメソッド」を用います。 クラスメソッドは「static」を用いて定義し、「クラス名::クラスメソッド名」 class Menu { private static $count = 0; public function __construct($name, $price, $image) { $this->name = $name; $this->price = $price; $this->image = $image; self::$count++; } public static function getCount(){ return self::$count; } } echo Menu::getCount();
class Player { private $myName; public function __construct($name){ $this->myName = $name; } public function walk() { echo $this->myName . "は荒野を歩いていた。" . "\n"; } } $player1 = new Player("戦士"); $player1->walk(); $player2 = new Player("魔法使い"); $player2->walk(); class Enemy { private $myName; public function __construct($name){ $this->myName = $name; } function attack() { echo $this->myName . "は、勇者を攻撃した。\n"; } } $enemies[] = new Enemy("スライム"); $enemies[] = new Enemy("モンスター"); $enemies[] = new Enemy("ドラゴン"); foreach ($enemies as $enemy) { $enemy->attack(); }
class Item { public $price; public $quantity; public function __construct($newPrice, $newQuantity){ $this->price = $newPrice; $this->quantity = $newQuantity; } public function getTotalPrice() { return $this->price * $this->quantity; } } $apple = new Item(120, 15); $total = $apple->getTotalPrice(); echo "合計金額は" . $total . "円です。\n"; $orange = new Item(85, 32); echo "合計金額は" . $orange->getTotalPrice() . "円です。\n";
class Item { public static $tax = 1.08; // public $price; // public $quantity; // public function __construct($newPrice, $newQuantity){ // $this->price = $newPrice; // $this->quantity = $newQuantity; // } public static function getTotalAmount($price, $quantity) { return round($price * $quantity * self::$tax); } } $total = Item::getTotalAmount(120, 15); echo "合計金額は" . $total . "円です。\n";