Php – use private instance methods as callbacks

callbackencapsulationphp

My particular scenario involves doing some text transformation using regular expressions within a private method. The private method calls preg_replace_callback, but is seems that callbacks need to be public on objects, so I'm stuck breaking out of the private world and exposing implementation details when I'd rather not.

So, in a nutshell: Can I use an instance method as a callback without losing encapsulation?

Thanks.

Best Solution

Yes, it seems you can:

<?php

//this works
class a {
   private function replaceCallback($m) { return 'replaced'; }

   public function test() {
        $str = " test test ";
        $result = preg_replace_callback('/test/', array($this, 'replaceCallback'), $str);
        echo $result;
   } 
}

$a = new a();
$a->test();


//this doesn't work
$result = preg_replace_callback('/test/', array(new a(), 'replaceCallback'), ' test test ');    
echo $result;

So it seems that preg_replace_callback(), or PHP's callback mechanism, is aware of the scope in which it was called.

Tested on 5.2.8