PHP - best way to initialize an object with a large number of parameters and default values

后端 未结 6 1106
旧巷少年郎
旧巷少年郎 2021-01-31 09:20

I\'m designing a class that defines a highly complex object with a ton (50+) of mostly optional parameters, many of which would have defaults (eg: $type = \'foo\'; $width

6条回答
  •  心在旅途
    2021-01-31 09:40

    I use this on a few of my classes. Makes it easy to copy and paste for rapid development.

    private $CCNumber, $ExpMonth, $ExpYear, $CV3, $CardType;
    function __construct($CCNumber, $ExpMonth, $ExpYear, $CV3, $CardType){
        $varsValues = array($CCNumber, $ExpMonth, $ExpYear, $CV3, $CardType);
        $varNames = array('CCNumber', 'ExpMonth', 'ExpYear', 'CV3', 'CardType');
        $varCombined = array_combine($varNames, $varsValues);
        foreach ($varCombined as $varName => $varValue) {$this->$varName = $varValue;}
    }
    

    Steps to use:

    1. Paste in and get the list of variables from your current __construct function, removing any optional parameter values
    2. If you haven't already, paste that in to declare your variables for your class, using the scope of your choosing
    3. Paste that same line into the $varValues and $varNames lines.
    4. Do a text replace on ", $" for "', '". That'll get all but the first and last that you'll have to manually change
    5. Enjoy!

提交回复
热议问题