Skip to content

Instantly share code, notes, and snippets.

@cgardner
Created April 21, 2012 02:08
Show Gist options
  • Save cgardner/2433264 to your computer and use it in GitHub Desktop.
Save cgardner/2433264 to your computer and use it in GitHub Desktop.
Self Modifying PHP
<?php
$var = <<<VAR
1
VAR;
// do stuff here
echo $var;
register_shutdown_function(function() {
$contents = file_get_contents(__FILE__);
$pattern = "\$var = <<<VAR\n%s\nVAR;";
$search_pattern = '@\\'. sprintf($pattern, '(.*)') .'@m';
preg_match($search_pattern, $contents, $matches);
$new_contents = preg_replace_callback($search_pattern, function($matches) {
return str_replace($matches[1], $matches[1] + 1, $matches[0]);
}, $contents);
file_put_contents(__FILE__, $new_contents, LOCK_EX);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment