インターフェイス
抽象クラスと似ています。
実装だけ可能です。
index.php
class 新クラス名 implements インターフェイスクラス名{}
実際のコードはこちら。
index.php
class Greet{
// 定数
const MORNING = 'おはよう';
const NOON = 'こんにちは';
const NIGHT = 'こんばんは';
}
class Time{
// 定数
const MORNING = '朝です';
const NOON = '昼です';
const NIGHT = '夜です';
}
interface Common1{
public function setGreet1($str);
public function getGreet1();
}
interface Common2{
public function setGreet2($str);
public function getGreet2();
}
class Introduction implements Common1, Common2{
private $name;
private $greet1;
private $greet2;
public function __construct($name, $greet1, $greet2){
$this->setName($name);
$this->setGreet1($greet1);
$this->setGreet2($greet2);
}
public function setName($str){
$this->name = $str;
}
public function getName(){
return $this->name;
}
public function setGreet1($str){
$this->greet1 = $str;
}
public function getGreet1(){
return $this->greet1;
}
public function setGreet2($str){
$this->greet2 = $str;
}
public function getGreet2(){
return $this->greet2;
}
public function getIntroduction(){
return $this->getName().$this->getGreet1().$this->getGreet2();
}
}
$user = new Introduction('太郎', Greet::NOON, Time::NOON);
echo $user->getIntroduction(); //太郎こんにちは昼です
・インターフェイスで定義したクラスはインスタンスを生成することはできない。
・インターフェイスは抽象クラスと違って一個以上実装することができる。
・publicやprivateなどの修飾子はpublic
のみ。
・インターフェイスで定義したメソッドは継承先で必ず実装しなければならない。
これらの特徴があります。
なのでこちらのコードはインターフェイスで定義したメソッドを実装先で定義していないのでエラーとなります。
index.php
interface Name{
public function UserName();
public function UserAge();
}
class User implements Name{
public function UserName(){
echo '太郎です';
}
//定義されていない
//public function UserAge(){
//echo '29才でちゅ!';
//}
}
$hoge = new User;
$hoge->UserName();
//$hoge->UserAge();
簡単ですが以上です。