PHP vol.32
- class vol.3
__construct
newした瞬間に呼ばれる関数
- Employee.class.php
<?php class Employee { public function __construct($id, $sei, $mei) { $this->setId($id); $this->setSei($sei); $this->setMei($mei); } public function getName() { return $this->sei." ".$this->mei; } } ?>
- 表示部
<?php require_once ('Employee.class.php'); $employee = new Employee("1", "えのもと", "しょうた"); echo $employee->getName()."は社員番号が".$employee->getId()."です。"; ?>
表示結果
えのもと しょうたは社員番号が1です。
初期値を定義できる
class Company { protected $money = 200000; //(省略) }
- セットすればその値になる。
classの継承
- 継承される側をスーパークラスという。
- 継承される側をサブクラスという。
サブクラスはスーパークラスの変数・メソッドを引き継ぐことができる。
class DinoEmployee extends Employee { }
- DinoEmployeeクラスはEmployeeクラスを伝承している。
- サブクラス通しの繋がりはない。
- サブクラスでスーパークラスの関数を書き換えることもできる。
//DinoEmployee.class.php class DinoEmployee extends Employee { public $hoge = 'hogehoge'; } //Employee.class.php class Employee { public $hoge = 'fugafuga'; } //表示 ($hogeをechoしたとして) hogehoge