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

后端 未结 6 1212
旧巷少年郎
旧巷少年郎 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:49

    Just to follow up with how I implemented this, based on one of Daff's solutions:

        function __construct($args = array()){
            // build all args into their corresponding class properties
            foreach($args as $key => $val) {                
                // only accept keys that have explicitly been defined as class member variables
                if(property_exists($this, $key)) {
                    $this->{$key} = $val;
                }
            }
        }
    

    Improvement suggestions welcomed!

提交回复
热议问题