preg_replace_callback() - 当前对象实例内的回调


preg_replace_callback() - Callback inside current object instance

警告:preg_replace_callback() [function.preg-replace-callback]:需要参数 2,'info',作为 [...] 中的有效回调

public function getDisplay(){
    $info = array_merge($this->info,array());
    return  preg_replace_callback('!'{'{('w+)'}'}!', 'info', $this->display);
}

在"MyClass"的公共函数中,当我从另一个类移动到这个类时停止工作。这是:

public function getEdit( $type){
    $all_info = $this->info;
    return preg_replace_callback('!'{'{('w+)'}'}!', 'all_info', $edit_contents);
}

两者都被清理干净了,现在我不能用以前的课程重新测试,因为它已经很久了。

我确定不允许使用变量,但它有效,所以我一无所知。

当我这样做时,正如某些堆栈溢出线程中所建议的那样,但显然它不适合在对象中使用:

public function getDisplay(){
    $display_info = $this->info;
    function display_info($matches) {
        global $display_info;
        return $display_info[$matches[1]];
    }
    return  preg_replace_callback('!'{'{('w+)'}'}!', 'display_info', $this->display);
}

所以我需要一些爱和指导,因为 php 本周让我发疯......

您可以使用支持

用于传递回调的方法之一,而不是使用匿名函数或更复杂的方法(请参阅有关回调的文档):

实例化对象的方法作为数组传递,该数组包含索引 0 处的对象和索引 1 处的方法名。

要将当前对象的"info"方法作为回调传递,只需执行以下操作:

array($this, 'info')

并将其传递到您想要使用"info"方法作为其他方法之一中的回调的任何位置。

正确的方法是使用闭包:

public function getDisplay() {
    // While $this support in closures has been recently added (>=5.4.0), it's
    // not yet widely available, so we'll get another reference to the current
    // instance into $that first:
    $that = $this;
    // Now we'll write that preg... line of which you speak, with a closure:
    return  preg_replace_callback('!'{'{('w+)'}'}!', function($matches) use($that) {
        return $that->info[$matches[1]];
    }, $this->display);
}

这解决了它:

public function getDisplay(){
    return  preg_replace_callback('!'{'{('w+)'}'}!', array(get_class($this), '_preg_replace_callback'), $this->display);
}
private function _preg_replace_callback($matches){
    return $this->info[$matches[1]];
}

我以前确实尝试过这种方法,但没有使用 get_class() 函数来包装$this。哦,打扰...