title: Inject code in a PHP closure
body: <p>I have an already defined closure and I want to inject code inside when I execute it.
  Here is an example:</p>
  
  <pre><code>$predefined = "print 'my predefined injected code&lt;br /&gt;';";
  $closure = function () {
    print 'hello&lt;br /&gt;';
  };
  call_user_func_array($closure, array());
  // output : hello
  </code></pre>
  
  <p>I want to mix 2 codes : a predefined one and the closure's one.
  After modification, I want my closure to look like this</p>
  
  <pre><code>$closure = function () {
    print 'my predefined injected code&lt;br /&gt;';
    print 'hello&lt;br /&gt;';
  };
  </code></pre>
  
  <p>Is it possible to insert some code in the closure before executing it ?</p>
  
  <p>Note: I can not use "create_function" that take the code as a string, so can be modified easily. The closures are already defined and are defined in a certain way (through a function that take a callback arg, not a string arg).</p>
  
  <p>Thanks for your help. </p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>Here is the  solution</p>
  
  <pre><code>function hackClosure($closure, $inject_code)
  {
      $reflection = new ReflectionFunction($closure);
      $tmp = $reflection-&gt;getParameters();
      $args = array();
      foreach ($tmp as $a) array_push($args, '$'.$a-&gt;getName() . ($a-&gt;isDefaultValueAvailable() ? '=\''.$a-&gt;getDefaultValue().'\'' : ''));
      $file = new SplFileObject($reflection-&gt;getFileName());
      $file-&gt;seek($reflection-&gt;getStartLine()-1);
      $code = '';
      while ($file-&gt;key() &lt; $reflection-&gt;getEndLine())
      {
          $code .= $file-&gt;current();
          $file-&gt;next();
      }
      $start = strpos($code, '{')+1;
      $end = strrpos($code, '}');
      return create_function(implode(', ', $args), substr($code, $start, $end - $start) . $inject_code);
  }
  
  $theClosure = function () { print 'something'; };
  
  $inject_code = "print ' to say';";
  
  $func = hackClosure($theClosure, $inject_code);
  $func();
  </code></pre>
  
  <p>It renders </p>
  
  <pre><code>something to say
  </code></pre>
  
  <p>instead of</p>
  
  <pre><code>something
  </code></pre>