title: Using array_push with closures overwriting previous element
body: <p>I have a strange problem. I am writing a callback-like system where some code calls a function in a class which adds the function to an array and then later on executes it. Here is my code:</p>
  
  <pre><code>class BaconClass {
      private $array;
  
      public function __construct() {
          $this-&gt;array = array();
      }
  
      public function AddBacon($function) {
          array_push($this-&gt;array, $function);
      }
  
      /* ... */
  
      public function GetBacon() {
          foreach($this-&gt;array as $function) {
              echo $function();
          }
      }
  }
  </code></pre>
  
  <p>Then I have some other code like this:</p>
  
  <pre><code>$bacon = new BaconClass();
  $bacon-&gt;AddBacon(function() {
      echo "Om nom nom";
  });
  
  /* And somewhere else I might have */
  
  $bacon-&gt;AddBacon(function() {
      echo "I like bacon";
  });
  
  /* And then after all of this I have */
  $bacon-&gt;GetBacon();
  </code></pre>
  
  <p>This code will only print:</p>
  
  <pre><code>I like bacon
  </code></pre>
  
  <p>I have made sure that the array being passed to the <code>AddBacon</code> function is actually working, but whenever I use <code>var_dump</code> to see what is inside the array after I add an element to it, it always shows one object, which is always the latest one added.</p>
  
  <p>Why is the code overwriting the previous element? If there is a better way to implement this code, I am open to suggestions.</p>
  
  <p><strong>What I have tried</strong></p>
  
  <p>I have tried using <code>$this-&gt;array[] = $function</code>, and I have also tried using <code>$this-&gt;array[count($this-&gt;array)] = $function</code>. Neither are working.</p>