对多个参数使用单个构造

Use single construct for multiple arguments

为了避免幻数和一些面向未来的努力,我希望能够声明一个具有多个组成元素的常量或变量,以允许单点在未来更改值.

例如

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

现在利益相关者想要更改 pdf 的背景颜色(需求签署后很长时间...)因此有很多地方可以更改此 rgb 值。方法 setFillColor($r, $g, $b) 来自第三方组件,因此我无法更改方法以接受单个数组参数。

有没有一种方法可以声明一个单独的构造,该构造将解压缩为 setFillColor() 方法的三个单独的必需参数,以便像下面这样的东西是可能的?

$my_color = [88, 38, 123];
$myPdf->setFillColor($my_color);
define('FOO', [1, 2, 3]);

function f($a, $b, $c) {
    var_dump($a, $b, $c);
}

f(...FOO);

https://3v4l.org/EGfFN

如果无法使用 ... 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)

对于 PHP 小于 7 的版本,您不能将常量设置为数组,而必须使用变量。

您的问题有 2 种方法。

首先,让我向您展示引用自 Clean Code Robert C Martin 的书(第 3 章:函数。函数参数 - 参数对象,第 43 页):

When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own.

正如我所见,您的值表示 RGB 颜色。为什么不将其包装为 class?

class RGB
{
    private $blue;
    private $green;
    private $red;

    public function __construct($red , $green , $blue)
    {
        $this->red = $red;
        $this->green = $gree;
        $this->blue = $blue;
    }

    /** others necesary methods **/
}

随心所欲地使用:

$my_color = new RGB(88, 38, 123);
$myPdf->setFillColor($my_color);

如果您需要使用其他颜色系统,只需使用一个界面:

interface Color { }

RGB 实现颜色

class RGB implements Color

还有一个新的颜色系统:

class CMYK implements Color
{
    private $cyan;
    private $magenta;
    private $yellow;
    private $black;

    public function __construct($cyan , $magenta , $yellow , black)
    {
        $this->cyan = $cyan;
        $this->magenta = $magenta;
        $this->yellow = $yellow;
        $this->black = $black;
    }
}

PDF 方法只需要接受一个实现 Color:

的 class
public function setFillColor(Color $color)

第二种方法,它不适合面向对象,但使用 function argument syntax for PHP >= 5.6 or call_user_func_array 来传递可变数量的参数。我不能在你的例子中推荐它(用于其他目的可能是个好主意),但它存在。