dongrong8972 2013-08-09 13:08
浏览 253

Eval代码不起作用

I am trying to make my own template engine, (Don't ask why!)

And will try making:

{{@Form::input("name")}}

In my rendering system i'll make this eval code:

    preg_match_all('/\{\{\@(.*?)\}\}/is',$data,$output);

    $out="";

    foreach ( $output[1] as $variables):
        $find = '{{@' . $variables . '}}';

        $data = str_replace($find, eval($variables), $data);
    endforeach;

But i am getting this error

 Parse error: syntax error, unexpected $end in /home/psafari/public_html/slt/classes/template.class.php(43) : eval()'d code on line 1

It should run "Form::input('something')" as specificed in the template engine. What am i doing wrong?

  • 写回答

1条回答 默认 最新

  • duanao4503 2013-08-11 00:28
    关注

    Despite the already uber-relevant comments against building a new templating engine, I'd suggest breaking the string found. Taking your example of {{@Form::input("name")}}, you'd have {{@CLASS_NAME::FUNCTION_NAME(params)}}. So using regex you could break the found string (as you already do), create an instance of or reference the class detected, then call the method parsed using a dynamic call (and obviously fail/error if either is not found).

    As for the parameters, you could avoid qualifiers (quotes in this case) and break on every comma, or use the qualifiers and parse it differently via regex again. Your call. For each parameter parsed and found, they'd be added to the function call. In order to avoid eval, and given the fact PHP does not support a random number of arguments (such as Python does with args and kwargs), having an array as the single parameter for the functions you'll use on the template files.

    You could also have sort of an 'interface' function that accepts a certain number of parameters that then receives the function (or class + function names), counts the number of parameters it finds and finally relays the call to the actual underlying function based on the correct number of parameters found. Though the more you add the more obscure the processing becomes - assuming users of your templating engine will be able to define new template methods, it's a very bad idea to use this second route (as you'd have to support up to N parameters on these interface functions).

    评论

报告相同问题?

悬赏问题

  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题