Oli B
Oli B

Reputation: 228

PHP Define Function without executing

I am currently developing an advertising module for a custom CMS, and using template tags to allow customers to add adverts into their pages through a WSYWIG page content editor.

Eg. {=advert_1}

On the frontend, this will be found through a regex and then be converted into a function, which will look to a database to select and display an advert

Template_tags.php

while ($advertRow = $advertResult->fetch_assoc()) {
    $advertGroupID = $advertRow['grpID'];
    $advert = "advert_";

    ${$advert . $advertGroupID} = showAdvert($advertGroupID);
}

This means {=advert_1} will be converted to showAdvert(1)

The problem I am having is that the showAdvert function will be run for all adverts regardless of whether or not it appears on the page, which then adds to the "views", even though the advert may not be displayed.

What I want is to just define the function without executing it, so when it appears in the page content, only then will the function will be executed.

Upvotes: 1

Views: 404

Answers (1)

Barmar
Barmar

Reputation: 781200

Use a function expression to create a closure.

${$advert . $advertGroupID} = function() use($advertGroupID) {
    showAdvert($advertGroupID);
};

To call the function, you need to put parentheses after it:

$name = 'advert_1';
echo $$name();

To use it with preg_replace_callback

preg_replace_callback("/\{=([^\{]{1,100}?)\}/", function($match) {
    return $match[1]();
}, $pageContent);

Upvotes: 1

Related Questions