dongyuedaochen8415 2018-01-24 14:18
浏览 78
已采纳

有没有办法明确忽略函数签名中声明的参数

Sometimes, especially with callbacks functions or inheritance/implementation case, I don't want to use some arguments in method. But they are required by the method interface signature (and I can't change the signature, let's say it's something required via Composer). Example:

// Assuming the class implements an interface with this method:
// public function doSomething($usefull1, $usefull2, $usefull3);

public function doSomething($usefull, $useless_here, $useless_here) {
    return something_with($usefull);
}
// ...

In some other languages (let's say Rust), I can ignore these arguments explicitly, which make the code (and intention) more readable. In PHP, it could be this:

public function doSomething($usefull, $_, $_) {
    return something_with($usefull);
}

Is this possible in PHP? Did I missed something?

Side note: it's not only for trailing arguments, it could be anywhere in the function declaration

  • 写回答

3条回答 默认 最新

  • doucheng1884 2018-01-24 14:42
    关注

    I think the best you can hope for is to give them unique names that will suggest that they will not be used in the call.

    Perhaps:

    function doSomething($usefull,$x1,$x2){
        return something_with($usefull);
    }
    

    Or:

    function doSomething($ignore1,$useful,$ignore2){
        return something_with($useful);
    }
    

    PHP wants to have arguments accounted for and uniquely named.


    Edit: If you want to avoid declaring variables that you won't use (but you know they are being sent), try func_get_args() and list(). This should make the code lean, clean, readable. (Demo)

    function test(){
        // get only use argument 2
        list(,$useful,)=func_get_args();
        echo $useful;
    }
    
    test('one','two','three');  // outputs: two
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集