如何从 file_get_contents 或函数中的文件运行 php 代码
我正在设计自己的 MVC 模式来简化创建主页的过程。我的模板系统需要我的控制器类来输出我的视图。这意味着我必须通过 php 函数输出该文件。我已经搜索了一段时间,似乎找不到解决方案。
如何通过 PHP 函数将表示某些源代码(“< ?”、“< ?php”、“? >”等)的字符串作为 php 运行?评估不会接受我的< ?标志(我读到该功能由于某种原因是垃圾)。
I am designing my own MVC pattern to ease the process of creating homepages. My templating system needs my controller class to output my views. This means I have to output the file through a php function. I have been searching for some a while now and can't seem to find a solution.
How can I, through a PHP function, run a string representing some source code ("< ?", "< ?php", "? >" and so on) as php? Eval would not take my < ? signs (and I read that function is crap for some reason).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以执行 php 代码并收集输出,如下所示:
http://www.php .net/manual/de/function.ob-get-contents.php
You could execute the php code and collect the output like this:
http://www.php.net/manual/de/function.ob-get-contents.php
只需包含()该文件就可以了。我没有深入研究源代码,但我相当确定这就是 Zend Framework 实现模板的方式。
Just include()ing the file instead should be fine. I've not dug that deeply into the source code but I'm fairly sure that's how Zend Framework implements templates.
按照 GordonM 的建议,用“include()”替换“echo file_get_contents()”完全按照需要工作。由于我太新,还不能投票,但根据我的需要,这是对标题问题的直接答案。
Replacing "echo file_get_contents()" with "include()" as GordonM suggested worked exactly as needed. can't upvote yet since I'm too new but for my needs this is the direct answer to the headlined question.
嗯, eval 本身并不是垃圾,如果你不小心在 eval 中允许什么,那么很容易创建一个安全漏洞(这可能不利于代码的可读性) 。
至于
标志,那是因为 eval 需要 php 代码,因此如果您不想将 php 与纯输出混合,请仅包含结束
?>
标记。然而,一般来说,您可以以更好的方式实现模板,尝试研究输出缓冲。
Well, eval is not crap per se, it's just easy to create a security hole with that if you're not careful about what you allow inside that eval (that, and maybe the fact that it can be bad for readability of the code).
As for the
<?
signs, that's because eval expects php code, so if you wan't to mix php with plain output, include just the closing?>
tag.In general however, you can implement templates in better fashion, try to look into output buffering.