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,);
In PHP 5.3, you be able to simply do:
$dbcon = /* ... */
preg_replace_callback('/PATTERN/',
function (array $matches) use ($dbcon) {
/* implementation here */
},
$subject
);
In the callback, you could call a function that returns the database connection? For example a singleton class which has the database connection.
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