views:

315

answers:

3

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.

+1  A: 

Can you create a separate helper class for text processing, and create the callback method within that class (it can be public there)? You can pass in a reference to the original class(object) if you need access to specific instance data.

The public interface to your main class remains consistent and clean, and you pull specific string processing out of a class it probably doesn't belong in anyway...

Zak
I like this method, but it'd require all code be refactored for the use of callbacks... seems too great a workaround.
Allain Lalonde
A: 

Can you not use protected? I'd need to know what the relationship of these two classes were in relation to each other to be more clear, but you should be able to extend the class and use the new protected methods you have inherited without making them public.

Hope this helps!

Cheers

+6  A: 

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

Tom Haigh
feature or bug? it works with 5.3rc2/win32.
VolkerK
Whoa, that's disturbingly awesome if they've taken the scope into account. I'll accept once I try it out.
Allain Lalonde
Confirmed on 5.2.9
jason