用eval(PHP)定义一堆函数

编程入门 行业动态 更新时间:2024-10-16 16:09:56
本文介绍了用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)定义一堆函数

本文发布于:2023-11-12 19:59:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   eval   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!