title: Convert a string to function (callable) and keep it cached
body: <p>I'm trying to make a little benchmarking script where I can enter short pieces of code for quick evaluation of my anticipations. I imagine it similar to jsPerf (but password-protected for security reasons).</p>
  
  <p>The main loop should look like this:</p>
  
  <pre><code>  public function run(&amp;$t, $count) {
      //Run setup function
      if(is_callable($this-&gt;setup))
        call_user_func($this-&gt;setup);
      //Save inital time
      $t($this-&gt;name);
      //THE MAIN LOOP
      for($i=0; $i&lt;$count; $i++) {
          call_user_func($this-&gt;fn);
      }
      //Save end time
      $t($this-&gt;name."_end");
      //return time difference
      return $t[$this-&gt;name."-".$this-&gt;name."_end"];
    }
  </code></pre>
  
  <p>However, this will only work with static approach - with functions defined while making the script:</p>
  
  <pre><code>//New instance of tester
  $b = new Benchmarker();
  $b-&gt;add(
    //Name
    "touch",
    //closure
    function() {
      touch("file.txt");
    },
    //Code seen in final reports
    "touch()"
  );
  </code></pre>
  
  <p>So as you see, I use <code>call_user_func</code>, not <code>eval</code>. Besides the fact that it's evil function in it's nature, I want to avoid it for performance reasons. If I'm testing a code that takes about 10ns to process and <em>eviluation</em> takes about 100ns, my results will be rather random.</p>
  
  <p>This is why I'm looking for a way to convert string to a callable object. You can think about it like one-time eval.</p>
  
  <pre><code>$callable = string_to_callable("function() {echo \"Hello world!\";}");
  $b-&gt;add(
    //Name
    "echo",
    //callable object
    $callable,
    //Code seen in final reports
    "echo \"...\""
  );
  </code></pre>
  
  <p><strong>Is that possible?</strong></p>
  
  <p><strong><sub>Note:</sub></strong></p>
  
  <p>I can see funny workaround using <code>include</code>:</p>
  
  <pre><code>//Code received from the user
  $code = "echo \"Hello world!\";";
  //Random name for a new function
  $rndname = "fn_".rand(0,100000);  //There are smarter ways to do this of course
  //String of the new function
  $func = "function $rndname() {{$code}}";
  //Define a filename
  $f = $rndname.".php";
  //Put the code in the file
  file_put_contents($f, "&lt;?php\n$func\n?"."&gt;");
  //Include the new script
  include $f;
  //Call the function
  call_user_func($rndname);
  //Delete the file
  unlink($f);
  </code></pre>
  
  <p>I really <strong>do hope</strong> that I <strong>won't need</strong> the code above!</p>