php函数参数类和接口

参数为类的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class {}
class D extends {}
class E {}
function f(C $c) {
echo get_class($c)."n";
}
f(new C);
f(new D);
f(new E);
?>

输出为

1
2
3
4
5
6
7
8
9
10
11
C
D
Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
thrown in - on line 8
?>

参数为接口的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface I { public function f(); }
class implements I { public function f() {} }
// This doesn't implement I.
class E {}
function f(I $i) {
echo get_class($i)."n";
}
f(new C);
f(new E);
?>

输出为

1
2
3
4
C
PHP Catchable fatal error: Argument 1 passed to f() must implement interface I, instance of E given, called in /code/main.php on line 13 and defined in /code/main.php on line 8
?>