在PHP中为Javascript生成小但有效的变量名的算法

I am working on a component framework in PHP that generates Javascript from server side and render it on client. Furthermore in Ajax communication the ids and value of components is transfered from client side to server. These ids are meaningful and large in length.

I would like to replace these bigs ids/variables with smaller names like _, _1, _2,_a, or _A So i need an algorithm that can generate next valid Javascript variable name such that whenever i call get_next_id function it gives me next unique variable name. Currently I checked uniqid in PHP but value returned is quite big.

Is there any way or algorithm to generate these type of names in PHP? Please note that the function must fisrt start from smallest possible variable name and then to higher order.

You can increment alphabetic characters in php:

for( $x = 'a'; $x!='z'; $x++) {
    echo "$x
";
  }

I believe something like the class below may do the trick. One could easily extend it to use more characters. I've used only lower case characters for simplicity.

class IdGenerator {
  function IdGenerator() {
    $this->id = 0;
  }

  function getId() {
   $ret = $this->getStringForId($this->id);
   $this->id += 1;
   return $ret;
  }

  function getStringForId($id) {
    $res = '';
    do {
      $res = chr( ord('a') + ($id % 26) ) . $res;
      $id = (int)($id / 26) - 1;
    } while ($id >= 0);
    return '_' . $res;
  }
}

The class just keeps a simple counter of how many ids it has generated so far. The function getStringForId generates a unique, minimal string for each index it is given.

If you run this test

$g = new IdGenerator();
for ($i = 0; $i < 30; $i++) {
  echo $g->getId() . "
";
}

You'll get

_a _b _c ... _y _z _aa _ab _ac _ad