用eval(PHP)定义一堆函数 [英] Defining a bunch of functions with eval (PHP)

查看:135
本文介绍了用eval(PHP)定义一堆函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是否接近可接受的东西?我需要为每个HTML标记提供一个函数,并且需要定义它们以便稍后在Heredoc字符串中使用。这是我的代码。

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.'>"; }');
}

这基本上处理了有关heredoc中的函数的Heredoc问题。一个简单的例子:

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

推荐答案

您可以使用PHP提供的 create_function ,但...因为代码很简单,为什么不使用一个函数来规定它们呢?

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}>";
}

你应该做什么。

作为一个后来的想法,您可能想查看一下 PHP DOM 可能是要走的路线,但需要一些时间来学习并习惯使用它。

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.

这篇关于用eval(PHP)定义一堆函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆