【问题标题】:preg_replace_callback() - Callback inside current object instancepreg_replace_callback() - 当前对象实例内的回调
【发布时间】:2012-06-22 21:46:07
【问题描述】:

警告: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);
}

两者都已清理干净,现在我无法重新测试以前的课程,因为它已经很久没有了。

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

当我这样做时,正如一些 stackoverflow 线程中所建议的那样,但显然它不是用于对象内:

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 让我发疯......

【问题讨论】:

    标签: php


    【解决方案1】:

    除了使用匿名函数或更复杂的方法,您可以只使用一种支持传递回调的方法 (see the documentation on callbacks):

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

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

    array($this, 'info')
    

    并将它传递到任何你想使用“info”方法的地方作为对象之一的其他方法中的回调。

    【讨论】:

    • +1 IMO 这是正确的方法,在其他具有回调的函数中也是如此。闭包似乎有点……局促、疯狂。
    【解决方案2】:

    正确的方法是使用闭包:

    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);
    
    }
    

    【讨论】:

    • 这太棒了!太好了以至于不能使用!但我的版本是 5.3.x Damn that Wamp!
    • 5.3 对上面的代码没问题,只是如果你是 5.2 或更低,闭包不起作用。
    • 5.4 约束仅用于在闭包中使用魔术变量$this,这就是我创建$that 的原因。这样做的一个问题是属性info 需要是public。
    • 这很好:function($matches) use($that) { return $that->getInfo()[$matches[1]]。但如果我没记错的话,PHP 不允许这样做...
    • @localhost 该语法被称为数组解引用,它是works as of 5.4。如果你被 5.3 卡住了,那就不用骰子了。
    【解决方案3】:

    这解决了它:

    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。哦,麻烦...

    【讨论】:

    • 你不应该需要 get_class()。 array($this, '_preg_replace_callback') 没问题。实际上,我认为您发布的解决方案行不通。
    • 它确实有效,但没有 get_class() 就无法正常工作...这是 PHP,去看看...
    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多