Skip to content

Instantly share code, notes, and snippets.

@miio
Created December 31, 2011 17:11
Show Gist options
  • Save miio/1544603 to your computer and use it in GitHub Desktop.
Save miio/1544603 to your computer and use it in GitHub Desktop.
PHPでクラスとインタフェース 型指定の関係
<?php
interface ExampleInterface{
function getHoge();
function getFuga();
function setAge(int $age);
}
class Example implements ExampleInterface{
function getHoge(){
}
function getFuga(){
}
function setAge(int $age){
}
}
//インタフェースで定義されているsetAgeメソッドが実装されてないのでエラーが出ます
class InvImplExample implements ExampleInterface{
function getHoge(){
}
function getFuga(){
}
}
//メソッドはインタフェースとは一緒ですが、インタフェースを実装していない状態です
class InvExample{
function getHoge(){
}
function getFuga(){
}
function setAge(int $age){
}
}
function HogeHoge(ExampleInterface $obj){
$obj->getHoge();
}
function HogeHoge2($obj){
$obj->getHoge();
}
HogeHoge(new Example());//これはOK
HogeHoge(new InvExample());//これは型エラー
HogeHoge(array());//これも型エラー
HogeHoge2(new Example());//これはOK
HogeHoge2(new InvExample());//これもOK
HogeHoge2(array());//これは型エラー
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment