Question

I'm working on converting an old define()-based language/translation system to a more flexible one (probably JSON-based, but it's still open).

As part of this conversion, I will need to convert from 42 .php files with several thousand strings each to whatever format I'll be using. Some of the defined strings reference other defines or use PHP code. I don't need to keep this dynamic behaviour (it's never really dynamic anyway), but I will need to have the "current" values at time of conversion. One define might look like this:

define('LNG_Some_string', 'Page $s of $s of our fine '.LNG_Product_name);

Since all defines have an easily recognizable 'LNG_' prefix, converting a single file is trivial. But I'd like to make a small script which handles all 42 in one run.

Ideally I'd be able to either undefine or redefine the define()'s, but I can't find a simple way of doing that. Is this at all possible?

Alternatively, what would be a good way of handling this conversion? The script will be one-off, so it doesn't need to be maintainable or fast. I just want it fully automated to avoid human error.

Was it helpful?

Solution

if speed is not important, so you can use get_defined_constants function.

$constans = get_defined_constants(true);
$myconst = array();
$myconst = $constans['user'];

$myconst will contain all constants defined by your script:-)
P.S: I'm not a good php coder, it was just a suggestion :-)

OTHER TIPS

You can't undefine constants, but you can generate your new scripts by utiliising them and the constant() function:

<?php
/* presuming all the .php files are in the same directoy */
foreach (glob('/path/*.php') as $file) {
  $contents = file_get_contents($file);
  $matches = array();
  if (!preg_match('/define\(\'LNG_(\w+)\'/', $contents, $matches) {
    echo 'No defines found.';
    exit;
  }

  $newContents = '';
  include_once $file;
  foreach ($matches as $match) {
    $newContents .= "SOME OUTPUT USING $match AS NAME AND " . constant($match) . " TO GET VALUE";
  }
  file_put_contents('new_'.$file, $newContents);
}
?>

Defined constants can't be undefined. They're immutable.

Perhaps what you can do is get in right before they're defined and modify them in certain circumstances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top