preg_replace_callback() - Callback inside current object instance

前端 未结 3 978
夕颜
夕颜 2020-12-11 14:06

Warning: preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, \'info\', to be a valid callback in [...]

public function getDisplay(         


        
相关标签:
3条回答
  • 2020-12-11 14:29

    Instead of using anonymous functions or more complex methods, you can just use one of methods supported for passing callbacks (see the documentation on callbacks):

    A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

    To pass "info" method of current object as a callback, just do the following:

    array($this, 'info')
    

    and pass it wherever you want to use "info" method as a callback within one of the objects other methods.

    0 讨论(0)
  • 2020-12-11 14:33

    The correct way to do this would be with a closure:

    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);
    
    }
    
    0 讨论(0)
  • 2020-12-11 14:50

    This solved it:

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

    I did try this approach before, but didn't use the get_class() function to wrap $this. Oh bother...

    0 讨论(0)
提交回复
热议问题