Passing more than one argument to a callback funct

2019-07-25 14:11发布

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?

3条回答
▲ chillily
2楼-- · 2019-07-25 14:28

In the callback, you could call a function that returns the database connection? For example a singleton class which has the database connection.

查看更多
乱世女痞
3楼-- · 2019-07-25 14:41

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

In PHP 5.3, you be able to simply do:

$dbcon = /* ... */
preg_replace_callback('/PATTERN/',
    function (array $matches) use ($dbcon) {
        /* implementation here */
    },
    $subject
);
查看更多
\"骚年 ilove
4楼-- · 2019-07-25 14:45

Artefacto's answer is correct (and should be accepted by the OP), but for anyone looking for a more generic solution, you may refer to this question on SE

查看更多
登录 后发表回答