Search code examples
phpargumentscustom-function

Is there a way to explicitely ignore agruments declared in function signature


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


Solution

  • 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