I have a configuration file which, amongst other things, defines a whole bunch of values and callables. I'm writing a development tool which needs to update some of the definitions in this file. I can't think of a way to do this which isn't just reading the file and writing my string at a certain point defined by a comment within the file.
Imagine my file looks like this:
<?php
$things = [
'a_thing' => 'some value',
'callable_thing' => function() {
return SomeClass();
}
// END THINGS
];
I'd like to insert a new array key into this array (the value of which might be any valid option), in alphabetical order. Is this possible, using Reflection maybe? Second best would be to place a specially formatted comment (i.e the "// END THINGS
" comment) as a "target" and insert before it, but I can't help but feel that's pretty hacky, and doesn't satisfy the alphabetical requirement.
I'm aware of the implications of self-mutating code. This is a developer tool and would only be used locally to automate common file->create->update tasks when setting up new projects.
You could use the var_export()
function to print the value of a variable in a way that can be evaluated. So you would load the file with include($filename);
, and modify the contents of $things
. Then you can update the file with:
$contents = '$things = ' . var_export($things, true) . ';';
file_put_contents($filename, $contents);