【发布时间】:2015-05-19 12:24:14
【问题描述】:
我想在我的 PHP 文件 constructor.php 中使用另一个 PHP 文件 template.php 的 HTML 字符串中的变量。
我在 Stackoverflow 上搜索了包含其他 PHP 文件内容的解决方法。我将以下代码包含在 constructor.php 中,因为已知它比使用 file_get_contents(); Source 更安全:
function requireToVar($file){
ob_start();
require($file);
return ob_get_clean();
}
constructor.php 的其余部分如下所示:
...
$sqli = mysqli_query($mysqli, "SELECT ...");
if(mysqli_num_rows($sqli) > 0){
$ii = 0;
while ($row = $sqli->fetch_assoc()) {
$ii++;
if($row['dummy']=="Example"){
$content.=requireToVar('template.php');
...
template.php 看起来像这样:
<?php echo "
<div class='image-wrapper' id='dt-".$row['id']."' style='display: none;'>
...
</div>
"; ?>
constructor.php 不会将 template.php 字符串中的 var $row['id'] 识别为自己的变量,也不会执行它。该变量绝对适用于constructor.php 中的其他代码。
如果我在$content.= 之后将template.php 的代码复制并粘贴到constructor.php 中,它就像一个魅力。但我想重组我的constructor.php,因为它变得越来越大,这样更容易定制。
我不知道如何更准确地描述这个问题,但我希望这个标题适合我的问题。
【问题讨论】:
-
您是否尝试将此 $row 变量作为另一个参数添加到函数 requireToVar() 中?
-
这种方式不太动态,因为我必须为我添加到
template.php中的字符串的每个附加变量自定义函数。 -
是的,但是您可以像 $content.=requireToVar('template.php', $row); $row 在 requireToVar 函数中不存在,您需要将其传递到那里
-
你为什么使用
ob_start();和ob_get_clean();?你为什么不做一个常规的require()而不做别的? -
@Novocaine 因为这对我不起作用。如果你写
$content.=require('template.php');constructor.php不会得到template.php的内容。我在我的问题中包含了一个指向 Stackoverflow-Thread 的链接。
标签: php html mysql templates constructor