Gaj*_*jus 14 php loops include
PHP缓存include请求吗?我想知道如何清理我的代码,并考虑使用更多includes.考虑以下方案.
[foreach answer] [include answer.tpl.php] [/foreach]
Run Code Online (Sandbox Code Playgroud)
这需要包括answer.tpl.php数百次.
它缓存了吗?它会对性能有影响吗?这被认为是一种好习惯吗?坏?
回应@Aaron Murray的回答
不,那不行.仅仅_once是防止包含同一文件不止一次的概念.(以防止例如覆盖常量值导致的错误)
实际的例子如下:
# index.php
<?php
$array = array('a', 'b', 'c');
$output = '';
foreach($array as $e)
{
$output .= require_once 'test.php';
}
echo $output;
# test.php
<?php
return $e;
Run Code Online (Sandbox Code Playgroud)
PHP缓存
include请求吗?
据我所知,PHP默认不缓存包含.但您的底层文件系统可能会这样做.因此,在您的示例中一遍又一遍地访问同一文件应该非常快.
如果遇到实际问题,首先需要对应用程序进行概要分析,以找出实际瓶颈的位置.所以除非你没有遇到任何问题,否则我会考虑使用包含无害的包含.
关于良好实践,我认为在本文中对此进行了很好的解释:当Flat PHP遇到Symfony时.
这不是高设计,它只是为了展示如何开始使模块更加模块化.您应该能够从包含文件中获取代码1:1,只需注意所有需要的模板变量都传递给函数(不要使用全局变量,它迟早会阻挡你的方式):
# in your answer.tpl.php
function answer_template(array $vars) {
extract($vars);
... your template code ...
}
# your script
array = array('a', 'b', 'c');
$output = '';
require('answer.tpl.php');
foreach($array as $e)
{
$output .= answer_template(compact('e'));
}
echo $output;
Run Code Online (Sandbox Code Playgroud)
你有没有考虑过:
require_once('answer.tpl.php')
or
include_once('answer.tpl.php')
Run Code Online (Sandbox Code Playgroud)
当然,您可以将"必需"文件仅包含在您希望它们包含的脚本中(仅限于真正需要它们的位置).
编辑:修改后的答案:
index.php - >
require_once('answer.php');
echo answer(); // This function can be called from anywhere in the scripts.
Run Code Online (Sandbox Code Playgroud)
answer.php - >
function answer() {
return '<div>This is the answer</div>';
}
Run Code Online (Sandbox Code Playgroud)
另外在旁注中你可以在你的函数中使用输出缓冲来捕获你的answer.php中的HTML(稍微清晰的分离HTML和php的方法).
回答上面的例子:
<?php
require_once('test.php');
$array = array('a', 'b', 'c');
$output = '';
foreach($array as $e)
{
$output .= test($e);
}
echo $output;
Run Code Online (Sandbox Code Playgroud)
<?php
function test($param) {
return $param;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |