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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面