我正在尝试做一些模板优化,我想知道是否可以做这样的事情:
function table_with_lowercase($data) {
$out = '<table>';
for ($i=0; $i < 3; $i++) {
$out .= '<tr><td>';
$out .= strtolower($data);
$out .= '</td></tr>';
}
$out .= "</table>";
return $out;
}
注意:当您运行此函数时,您不知道 $data 是什么。
结果:
<table>
<tr><td><?php echo strtolower($data) ?></td></tr>
<tr><td><?php echo strtolower($data) ?></td></tr>
<tr><td><?php echo strtolower($data) ?></td></tr>
</table>
一般情况:任何可以评估(编译)的东西都可以。每当存在未知变量时,该变量和包含该变量的函数都会以字符串格式输出。
下面是另一个示例:
function capitalize($str) {
return ucwords(strtolower($str));
}
如果 $str 是“HI ALL”,则输出为:
If $ str 未知,则输出为:
在这种情况下,调用函数会更容易(即
),但是示例before 允许您预编译 PHP 以使其更加高效
I'm trying to do some templating optimizations and I'm wondering if it is possible to do something like this:
function table_with_lowercase($data) {
$out = '<table>';
for ($i=0; $i < 3; $i++) {
$out .= '<tr><td>';
$out .= strtolower($data);
$out .= '</td></tr>';
}
$out .= "</table>";
return $out;
}
NOTE: You do not know what $data is when you run this function.
Results in:
<table>
<tr><td><?php echo strtolower($data) ?></td></tr>
<tr><td><?php echo strtolower($data) ?></td></tr>
<tr><td><?php echo strtolower($data) ?></td></tr>
</table>
General Case: Anything that can be evaluated (compiled) will be. Any time there is an unknown variable, the variable and the functions enclosing it, will be output in a string format.
Here's one more example:
function capitalize($str) {
return ucwords(strtolower($str));
}
If $str is "HI ALL" then the output is:
If $str is unknown then the output is:
<?php echo ucwords(strtolower($str)); ?>
In this case it would be easier to just call the function (ie. <?php echo capitalize($str) ?>
), but the example before would allow you to precompile your PHP to make it more efficient
发布评论
评论(3)
定义 CSS 样式并让客户端而不是服务器端完成工作。
...
Define a CSS style and make the client side do the work, instead of the server side.
<span="change_case">...</span>
这绝对是可能的。但是,为 php 编写一个有效的优化编译器并不是一件容易的事。过于简单化的方案可能不会带来显着的好处。对于一个好的人来说,其好处甚至值得怀疑。
It's definitely possible. But, writing an effective optimizing compiler for php is no easy task. A simplistic one would probably not offer significant benefit. The benefit is even questionable for a good one.
最好的选择可能是使用单独的模板语言来生成优化的 PHP 代码。 Smarty 是一个受欢迎的选择。
Your best bet is probably to use a separate templating language that generates optimised PHP code. Smarty is a popular choice.