【问题标题】:Is there a way to explicitely ignore agruments declared in function signature有没有办法显式忽略函数签名中声明的参数
【发布时间】:2018-01-24 14:18:55
【问题描述】:

有时,特别是对于回调函数或继承/实现情况,我不想在方法中使用一些参数。但是方法接口签名需要它们(我不能更改签名,假设这是通过 Composer 需要的东西)。示例:

// 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);
}
// ...

在其他一些语言(比如 Rust)中,我可以显式忽略这些参数,这使代码(和意图)更具可读性。在 PHP 中,可能是这样的:

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

这在 PHP 中可行吗?我错过了什么吗?

旁注:它不仅用于尾随参数,还可以在函数声明中的任何位置

【问题讨论】:

    标签: php arguments custom-function


    【解决方案1】:

    我认为你能期望的最好的结果就是给他们一个独特的名字,这表明他们不会在通话中使用。

    也许:

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

    或者:

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

    PHP 希望对参数进行解释和唯一命名。


    编辑:如果您想避免声明您不会使用的变量(但您知道它们正在被发送),请尝试func_get_args()list()。这应该使代码精简、干净、可读。 (Demo)

    function test(){
        // get only use argument 2
        list(,$useful,)=func_get_args();
        echo $useful;
    }
    
    test('one','two','three');  // outputs: two
    

    【讨论】:

    • 好的,谢谢。我只是在接受你的之前等待其他答案,以防其他人知道不同的方法。
    • @rap-2-h 没关系,作为 StackOverflow 上的良好做法,我建议您不要急于绿色勾号。
    • @rap-2-h 我突然想到func_get_args()list() 将有效地“清理”你的函数。看看我的更新。
    【解决方案2】:

    为可选参数分配默认值。

    function doSomething($usefull,$useless1=null,$useless2=null){
        return something_with($usefull); 
        }
    

    现在.... 参数 1 是必需的 参数 2 是可选的 参数3是可选的

    调用函数如..

    doSomething($data);
    doSomething($data,$anotherData);
    doSomething($data,$anotherData,$anotherData1);
    

    【讨论】:

    • 是的,但这与 OP 的要求无关。无用的论点可以在任何位置。
    • 还将第一个参数设为可选(有用等于 null),然后检查函数中的所有参数并做任何你想做的事情。
    • 这不是一个解决方案(尽管收到了某人的支持)。为这些参数设置默认值不会使这些值无效。 null 值只会在调用函数时在没有参数的情况下分配。 OP 说他无法控制函数调用;只有函数声明。
    【解决方案3】:

    您的具体对象不完全适合接口,因此您可以在它们之间添加一个适配器类。所以界面保持原样,你的对象得到它真正需要的东西。

    class Adapter extends CustomInterface
    {
        function doSomething($ignore1,$useful,$ignore2){
            return $customClass->something_with($useful);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 2020-07-02
      • 2011-09-10
      • 1970-01-01
      • 2015-03-08
      • 2014-02-28
      • 2017-01-16
      • 1970-01-01
      相关资源
      最近更新 更多