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

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

    I can think of two ways of doing that. If you want to keep your instance variables you can just iterate through the array passed to the constructor and set the instance variable dynamically:

         $val) {
                    $name = '_' . $key;
                    if(isset($this->{$name})) {
                        $this->{$name} = $val;
                    }
                }
            }
        }
    
        ?>
    

    When using the array approach you don't really have to abandon documentation. Just use the @property annotations in the class body:

     'default_type',
            'width' => 100,
            'interactive' => true
        );
    
        function __construct($args){
            $this->_instance_params = array_merge_recursive($this->_instance_params, $args);
        }
    
        public function __get($name)
        {
            return $this->_instance_params[$name];
        }
    
        public function __set($name, $value)
        {
            $this->_instance_params[$name] = $value;
        }
    }
    
    ?>
    

    That said, a class with 50 member variables is either only used for configuration (which can be split up) or it is just doing too much and you might want to think about refactoring it.

提交回复
热议问题