2010-12-12 59 views
0

這是否接近某些可以接受的東西?我需要爲每個HTML標記提供一個函數,並且需要定義它們以便稍後在Heredoc字符串中使用。這是我的代碼到目前爲止。用eval(PHP)定義一堆函數

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

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

這基本上處理有關heredoc中的函數的Heredoc問題。一個簡單的例子:

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

我做的所有代碼的心臟,所以請不要驚訝,如果他們包含任何錯誤。我還沒有執行評估函數,但它看起來沒問題。不管怎樣,我的問題是:這是好,還是不如去做到這一點的硬路:

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

等等..?

回答

5

你可以使用PHP提供的create_function,但是...由於代碼很簡單,爲什麼不用一個函數來統一它們呢?

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

應該做你以後的事情。

作爲一個後來的想法,你可能想看看PHP DOM,因爲這可能是要走的路線,但需要一些時間來學習和習慣使用它。

+0

老實說,我在Google那裏很努力地爲那個寶貝!非常感謝:-) – 2010-12-12 19:43:48

1

如果你還是要用一個醜陋的黑客攻擊,我寧願做:

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

$html = 'create_html'; 

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

這需要額外的參數,不,謝謝:P – 2010-12-12 20:18:00

2

如果你可以用更精細的活:

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

然後就足夠了定義一個:

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

將比多個EVAL往返定義函數更快。

0

如果您使用PHP 5.3,則可以使用閉包。 優於create_function。避免eval()