// myConfig.php
<?php return (array (
));
// ClassTest.php
<?php
class ConfigActions
{
protected $path;
protected $array;
function get($name = null)
{
if(isset($name)){
return $this->array[$name] ?? null;
} else {
return $this->array ?? [];
}
}
function set(array $array)
{
$this->array = $array;
}
function edit(array $data_array)
{
$this->array = array_merge(($this->array??[]), $data_array);
}
function delete()
{
foreach (func_get_args() as $config_key) {
unset($this->array[$config_key]);
}
}
function save(string $path=null)
{
$save_path = ($path ?? $this->path);
if(is_null($save_path)){
throw new Exception('No path to save');
}
$data = is_array($this->array) ? $this->array : [];
$config = "<?php return (".var_export($data, true).");";
$result = file_put_contents($save_path, $config, LOCK_EX);
if($result === false){
throw new Exception('Error saving');
}
return $result;
}
}
class ConfigContainer extends ConfigActions
{
function __construct($config_file)
{
$this->path = $config_file;
if(!file_exists($config_file) || !is_file($config_file)) {
throw new \Exception('File not exist');
} elseif(!is_readable($config_file)) {
throw new \Exception('Can not access file');
}
$settings = include($config_file);
if(!is_array($settings)) {
throw new \Exception('Config is not array');
}
$this->array = $settings;
}
}
/*
$config = new ConfigContainer('config_path', 'save_path_with_filename')
// Удаляю не существующий элемент
var_dump($config ->delete('g85masf46y4y'));
var_dump($test_config->get());
var_dump($test_config->save());
*/
Add a code snippet to your website: www.paste.org