我可以使用私有实例方法作为回调吗?

问题描述:

我的特定情况包括在私人方法中使用正则表达式进行一些文本转换。私有方法调用preg_replace_callback,但似乎回调需要对对象是公共的,所以我坚持打破私人世界,并暴露实施细节,而不是。

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?

谢谢。

是的,你似乎可以:

<?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;

所以看来 preg_replace_callback()或PHP的回调机制,知道调用它的范围。

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

在5.2.8上测试