How can PHP features like visibility modifiers and magic methods be utilized to enhance the functionality and maintainability of classes like Cfg in object-oriented programming projects?
Visibility modifiers can be used to control access to class properties and methods, ensuring that only relevant parts of the class are accessible from outside. Magic methods can be utilized to implement common functionality like property overloading or method overloading, reducing code duplication and improving maintainability. By using these features in a class like Cfg, we can encapsulate its properties and methods effectively, making it easier to manage and extend in object-oriented programming projects.
class Cfg {
private $config = [];
public function __construct($config) {
$this->config = $config;
}
public function getConfigValue($key) {
return $this->config[$key] ?? null;
}
public function __get($key) {
return $this->getConfigValue($key);
}
public function __set($key, $value) {
$this->config[$key] = $value;
}
}
$config = ['key1' => 'value1', 'key2' => 'value2'];
$cfg = new Cfg($config);
echo $cfg->key1; // Output: value1
$cfg->key3 = 'value3';
echo $cfg->key3; // Output: value3