Can I use private instance methods as callbacks?

痞子三分冷 提交于 2019-12-01 13:50:58

问题


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:


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




回答2:


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...




回答3:


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



来源:https://stackoverflow.com/questions/1028035/can-i-use-private-instance-methods-as-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!