Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

php - preg_replace_callback() - Callback inside current object instance

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

public function getDisplay(){
    $info = array_merge($this->info,array());

    return  preg_replace_callback('!{{(w+)}}!', 'info', $this->display);
}

In a public function from "MyClass", stopped working when I moved from another class to this one. Which was:

public function getEdit( $type){
    $all_info = $this->info;

    return preg_replace_callback('!{{(w+)}}!', 'all_info', $edit_contents);
}

Both are cleaned up, and now I can't retest with previous class because it's already long gone.

I'm sure using variables is not allowed, but it was working, so I'm clueless.

When I do this, as suggested in some stackoverflow thread, but obviously it's not made to be used within objects:

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

So I need some love and guidance cuz php is driving me crazy this week...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...