Created
December 31, 2011 17:11
-
-
Save miio/1544603 to your computer and use it in GitHub Desktop.
PHPでクラスとインタフェース 型指定の関係
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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