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

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

    Another approach is to instantiate the class with a FooOptions object, acting solely as an options container:

    _options = $options;
        }
    }
    
    
    class FooOptions
    {
        private $_type = 'default_type';
        private $_width = 100;
        private $_interactive = true;
    
        public function setType($type);
        public function getType();
    
        public function setWidth($width);
        public function getWidth();
    
        // ...
    }
    

    Your options are well documented and you have an easy way to set/retrieve them. This even facilitates your testing, as you can create and set different options objects.

    I don't remember the exact name of this pattern, but I think it's Builder or Option pattern.

提交回复
热议问题