Da'sBlog

php函数参数类和接口

参数为类的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
class C {}
class D extends C {}
// This doesn't extend C.
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
<?php
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
<?php
interface I { public function f(); }
class C 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
<?php
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
?>
坚持原创技术分享,您的支持将鼓励我继续创作!