这里有两种方法:
/**
* @return int
*/
public function add ($a, $b)
{
return $a+$b;
}
/**
* @return array
*/
public function toArray ($a, $b)
{
return array($a, $b);
}
基于PhPDoc和代码本身,没有人可以质疑这些方法的结果。但是如果我用Phpunit来嘲笑他们呢?
$this->getMock ('MyClass');
$this->expects($this->once())->method('add')->willReturn(array(1,2,3,4));
$this->expects($this->once())->method('toArray')->willReturn(7);
在本例中,我故意忽略了结果值的类型。但是没有人会抛出异常“嘿,类型不匹配!”我知道它是Php,但我能以某种方式强制使用这些类型吗?
发布于 2015-12-20 21:57:28
不是使用PhpDoc,但是从PHP7开始,您可以执行以下操作
<?php
declare(strict_types=1);
class MyClass
{
public function add ($a, $b) : int
{
return $a+$b;
}
public function toArray ($a, $b) : array
{
return array($a, $b);
}
}
declare(strict_types=1)
行很重要,因为如果不这样的话,错误的类型将被强制使用而不会出错:
Strict typing对返回类型声明也有影响。在默认的弱模式下,如果返回值还不是正确的类型,那么它们将被强制为正确的类型。在强模式下,返回值的类型必须正确,否则会抛出TypeError。
https://stackoverflow.com/questions/32012817
复制相似问题