views:

29

answers:

2

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?

A: 

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
);
Artefacto
Could you use `create_function()`?
Peter Ajtai
@Peter I consider that an abomination... creating a function from a string... It's the `eval` cousin. And it wouldn't solve the problem because it cannot create a function bound to outside variables. We're back to `global`.
Artefacto
@Artefacto - `create_function()` does take arguments fwiw - `string create_function ( string $args , string $code )`. I understand the point about `eval`.
Peter Ajtai
@Peter The problem is that you can't pass those arguments to `preg_callback_function` for them to be passed back to the function. That's precisely the OP's problem (see his question).
Artefacto
@Artefacto - Oh yeah. BTW the order of arguments for `preg_callback_function()` is `pattern`, `callback`, `subject`, not `pattern`, `subject`, `callback` - http://php.net/manual/en/function.preg-replace-callback.php
Peter Ajtai
@Pete Thanks; I fixed it.
Artefacto
A: 

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

Leon