Search code examples
phpargument-unpacking

Use single construct for multiple arguments


In an effort to avoid magic numbers and a bit of future-proofing, i'd like to be able to declare a single constant or variable with multiple constituent elements, to enable a single point to change the values in future.

For example

$myPdf->setFillColor(88, 38, 123) # using this method many times in a routine.

Now the stakeholders want to change the background colour of the pdf (long after requirements sign-off...) so there are many places to change this rgb value. The method setFillColor($r, $g, $b) is from a third party component so I can't change the method to accept a single array argument.

Is there a way to declare a single construct which will unpack into the three, individual, required arguments for the setFillColor() method so something like the following is possible?

$my_color = [88, 38, 123];
$myPdf->setFillColor($my_color);

Solution

  • define('FOO', [1, 2, 3]);
    
    function f($a, $b, $c) {
        var_dump($a, $b, $c);
    }
    
    f(...FOO);
    

    See https://3v4l.org/EGfFN.

    If you cannot use the ... operator because you're using an ancient version of PHP, you can also use call_user_func_array:

    call_user_func_array([$myPdf, 'setFillColor'], MY_COLOR)
    

    For PHP versions < 7 you can't set the constant to an array, you'll have to use a variable instead.