这不是一个接口的东西。为了避免在消费者中进行类型检查,方法应该只返回一种类型。由于reduced number of execution pathes through the code,它使代码更容易理解。
例如,这增加了不必要的复杂性:
function get_users()
{
// some code returning array when users have been found
// or null when no users have been found
}
$users = get_users();
if (!is_null($users)) {
foreach ($users as $user) {
// do something with $user
}
}
如果get_users() 在未找到用户时只返回一个空数组,您可以将消费代码简化为只读
foreach (get_users() as $user) {
// do something with $user
}
此外,凭借Liskov's Substitution Principle,作为超类型子类型的任何类都需要在使用超类型的消费者中可互换使用。如果消费者需要一个整数,您可能不会返回一个字符串,因为这可能会破坏消费者。这同样适用于实现接口的类和该接口的消费者,例如
interface Contract
{
/** @return array */
public function fn();
}
现在假设 A implements Contract 并返回数组,而 B implements Contract 并返回数组或 null。当 B 返回 null 时,我期望数组的消费者现在会中断:
function fn(Contract $instance)
{
// will break when B returns null
foreach ($instance->fn() as $foo) {
// do something with $foo
}
}
由于 PHP 目前无法强制执行返回类型,因此由开发人员在 DocBlock 中指明它并确保实现或子类型化的类遵循该返回类型。
话虽如此,如果合约定义了多种可能的返回类型,消费者必须确保它可以处理它们。然而,这又意味着不受欢迎的类型检查。