【问题标题】:PHP interfaces. Different return typePHP 接口。不同的返回类型
【发布时间】:2014-03-22 11:10:19
【问题描述】:

PHP 中的接口应该返回相同的类型吗? 我的朋友告诉我它应该返回相同的类型。(为了良好的做法) 我知道 PHP 是动态类型语言,这是不可能的。

例如:

    interface idReturn
{
   //Return INT
   public function getById($id);
}

interface arrayReturn
{
    //Return array
    public function getByData($data);
}

这是好的做法吗?

【问题讨论】:

    标签: php interface


    【解决方案1】:

    这不是一个接口的东西。为了避免在消费者中进行类型检查,方法应该只返回一种类型。由于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 中指明它并确保实现或子类型化的类遵循该返回类型。

    话虽如此,如果合约定义了多种可能的返回类型,消费者必须确保它可以处理它们。然而,这又意味着不受欢迎的类型检查。

    【讨论】:

      【解决方案2】:

      他大概是这个意思:

      interface I {
          public function f();
      }
      
      class A implements I {
          public function f() {
              return 1; // int
          }
      }
      
      class B implements I {
          public function f() {
              return 'a'; // string
          }
      }
      

      您是否想要这完全取决于您为I::f 定义的合同。合同应该放在单独的文档中,因为 PHP 缺乏对正式指定它们的支持(这不是 PHP 特定的,大多数语言都是这种情况,值得注意的例外是 D 和 Eiffel)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-20
        • 2015-09-06
        • 1970-01-01
        • 2015-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多