PHP为了解决自己是弱类型语言在调用方法是传参类型可能导致的问题,引入了参数提示,看代码
1 <html> 2 <body> 3 <?php 4 class Man { 5 private $name; 6 7 function getName() { 8 return $this->name; 9 } 10 11 function setName($name) { 12 $this->name = $name; 13 } 14 } 15 16 class Wrong {} 17 18 function callMan(Man $man) { 19 echo "Hey " . $man->getName(); 20 } 21 22 $man = new Man(); 23 $man->setName('Jack'); 24 25 callMan($man); 26 callMan(new Wrong()); 27 ?> 28 </body> 29 </html>
再看输出
Hey Jack
Catchable fatal error: Argument 1 passed to callMan() must be an instance of Man, instance of Wrong given, called in D:\www\index.php on line 26 and defined in D:\www\index.php on line 18
由于callMan()函数传入参数类型不是Man,导致了catchable fatal error,至此我觉得PHP慢慢变得自相矛盾,许多自己的特性给自己造成了困扰,然后又出新特性来解决原来的问题