Michael McMillan
Michael McMillan

Reputation: 135

Defining a bunch of functions with eval (PHP)

Is this anywhere near something acceptable? I need a function for each HTML tag, and they need to be defined for later use in a Heredoc string. This is my code so far.

<?php
$tags = array (h1, h2, h3, b, i);

foreach ($tags as $key => $value)
{
    eval ('function '.$value.' ($str) { return "<'.$value.'>$str</'.$value.'>"; }');
}

This basically takes care of the Heredoc problem concerning functions within heredoc. A quick example:

<<<example
<h1>This is ordinary HTML</h1>
{$h1('This is HTML via. PHP')}
example;

I did all the code over by heart, so please don't be suprised if they contain any errors. I haven't executed the eval-function yet, but it looks alright. Anyway, my question would be: Is this okay, or is it better to go do it the hard-way:

function h1 ($str) { return ...; }
function h2 ($str) { return ...; }
function h3 ($str) { return ...; }
function b ($str) { return ...; }
function i ($str) { return ...; }

And so on ..?

Upvotes: 0

Views: 868

Answers (4)

scoates
scoates

Reputation: 853

If you're on PHP 5.3, you could use closures. Far superior to create_function. Avoid eval().

Upvotes: 0

Jim
Jim

Reputation: 18853

You could use the create_function provided by PHP but...Since the code is simple why not just use one function to rule them all?

function createTag($tag, $text) {
     return "<{$tag}>{$text}</{$tag}>";
}

Should do what you are after.

As an after thought, you might want to check out the PHP DOM as that would probably be the route to go, but will take some time to learn and get used to using it.

Upvotes: 5

mario
mario

Reputation: 145482

If you could live with a more elaborate:

 <h1>This is ordinary HTML</h1>     
 {$h->h1("This is HTML via PHP.")}

Then it would suffice to define a single:

class html {
    function __call($name, $args) {
        return "<$name>$args[0]</$name>";
    }
}
$h = new html();

Would be faster than multiple eval roundtrips to define functions.

Upvotes: 2

Andre
Andre

Reputation: 3181

If you're going to use an ugly hack anyway, I'd much rather do:

function create_html($tag, $val) {
    return "<{$tag}>{$val}</{$tag}>";
}

$html = 'create_html';

<<<example
<h1>Test</h1>
{$html('h2','Another test')}
example;

Upvotes: 1

Related Questions