问题描述
我正在写一个内容管理系统。该页面的管理进入内容页面,当他进入由特殊字符包围一个数字,它是由观众的屏幕上的一个数据库条目取代解析时。要在解析做到这一点,我使用preg_replace_callback()。但是,我无法将数据库连接变量传递到回调函数,所以它不会起作用。作为一个短期的解决办法,我只是试图让数据库连接一个全局变量在这一个实例,并使用它的方式,但是这不过是一个草率的组装机,为长期不是一个好主意。
I'm writing a content management system. The page admin enters content for a page and, when he enters a number surrounded by special characters, it's replaced by a database entry on the viewer's screen when parsed. To accomplish this in the parsing, I'm using preg_replace_callback(). However, I can't pass my database connection variable into the callback function, so it won't work. As a short-term workaround I'm just trying to make the database connection a global variable in this one instance and use it that way, but this is nothing but a sloppy kludge and not a good idea for the long-term.
有谁知道如何解决我的问题,甚至是不同的,在做什么,我想要做的更好的办法?
Does anyone know how to solve my problem or even a different, better way of doing what I'm trying to do?
推荐答案
您必须创建一个函数/方法包装它。
You have to create a function/method that wraps it.
class PregCallbackWrap {
private $dbcon;
function __construct($dbcon) { $this->dbcon = $dbcon; }
function callback(array $matches) {
/* implementation of your callback here. You can use $this->dbcon */
}
}
$dbcon = /* ... */
preg_replace_callback('/PATTERN/',
array(new PregCallbackWrap($dbcon), 'callback'), $subject,);
在PHP 5.3,你可以简单地做:
In PHP 5.3, you be able to simply do:
$dbcon = /* ... */
preg_replace_callback('/PATTERN/',
function (array $matches) use ($dbcon) {
/* implementation here */
},
$subject
);
这篇关于传递多个参数的回调函数(使用PHP 5.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!