donglu9825 2014-03-22 11:10
浏览 31
已采纳

PHP接口。 不同的退货类型

Should interfaces in PHP return the same types ? My friend told me that it should return the same types.(for good practice) I know that PHP is dynamic type language and it isn't possible.

For example:

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

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

Is it good practice or not?

  • 写回答

2条回答 默认 最新

  • douxin2003 2014-03-22 11:12
    关注

    It's not an interface thing. To avoid type checking in the consumers, a method should return one type only. It makes for easier to understand code due to the reduced number of execution pathes through the code.

    For instance, this adds unnecessary complexity:

    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
        }
    }
    

    If get_users() would simply return an empty array when no users have been found, you can simplify the consuming code to just read

    foreach (get_users() as $user) {
        // do something with $user
    }
    

    Also, by virtue of Liskov's Substitution Principle, any classes that are subtypes of a supertype need to be usable interchangeably in a consumer using the supertype. If the consumer expects an integer, you may not return a string since that might break the consumer. The same holds true for classes implementing an interface and consumers of that interface, e.g.

    interface Contract
    {
        /** @return array */
        public function fn();
    }
    

    Now assume A implements Contract and returns array, while B implements Contract and returns array or null. My consumer expecting an array will now break when B returns null:

    function fn(Contract $instance)
    {
        // will break when B returns null
        foreach ($instance->fn() as $foo) {
            // do something with $foo
        }
    }
    

    Since PHP cannot currently enforce a return type, it's up to the developer to indicate it in the DocBlock and to make sure the implementing or subtyped classes adhere to that return type.

    With that said, if the contract defines multiple possible return types, the consumer has to make sure it can handle them. However, that again means undesirable type checking.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi