Defining a bunch of functions with eval (PHP)

喜你入骨 提交于 2019-12-08 09:21:21

问题


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 ..?


回答1:


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.




回答2:


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.




回答3:


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;



回答4:


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



来源:https://stackoverflow.com/questions/4423593/defining-a-bunch-of-functions-with-eval-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!