Php 对页面使用更好的包含?

Php 对页面使用更好的包含?,php,include,Php,Include,现在,我使用include的方式是为其他页面提供页眉、页脚和一些内容 这将导致更多的包含,而不是我真正想要的,因为我需要为包含添加更多内容 例如: <!DOCTYPE html> <?php include('header.php'); ?> <body> <?php include('body-top.php'); custom html </?php include('footer.php'); </body> 听起来像

现在,我使用include的方式是为其他页面提供页眉、页脚和一些内容

这将导致更多的包含,而不是我真正想要的,因为我需要为包含添加更多内容

例如:

<!DOCTYPE html>
<?php include('header.php'); ?>
<body>

<?php include('body-top.php');
   custom html
</?php include('footer.php');
</body>

听起来像是一份工作

看起来像这样

<?php
require 'Smarty/libs/Smarty.class.php';

$smarty = new Smarty;

$smarty->assign('title','Hello World');
$smarty->assign('hello','Hello World, this is my first Smarty!');
$smarty->display('test.tpl');
?>

test.tpl

<html>
  <head>
    <title>{$title}</title>
  </head>
  <body>
    {$hello}
  </body>
</html>

{$title}
{$hello}

或者更好的方法是,使用一些PHP MVC框架,这将为您提供更多的东西(不仅仅是模板系统)

您可以将包含的文件转换为函数。PHP有一个巧妙的技巧,即只有在到达代码的该部分时,才会执行花括号(即
{
}
)之间的任何内容。这包括PHP标记之外的HTML代码

这可能是我们的“header.php”文件,在这里我们将当前代码包装到一个函数中

<?php function doHeader($title) {  ?>
<html>
<head> 
<title><?php echo $title; ?></title>
</head>
<?php  }  ?>
这就产生了输出

<!DOCTYPE html>
<html>
<head> 
<title>My page title</title>
</head>
<body></body>
</html>

我的页面标题

您的包含内容已经很少,无需对其进行优化


另外,不要注意那些建议Smarty或MVC的人,因为这将显著增加包含的数量(当然,作为其他好处的交换)

这很容易做到:

index.php

$title = 'Hello World!';
include 'content.php';
<!DOCTYPE html>
<html>
<head> 
<title><?php echo $title; ?></title>
</head>
<body></body>
</html>
content.php

$title = 'Hello World!';
include 'content.php';
<!DOCTYPE html>
<html>
<head> 
<title><?php echo $title; ?></title>
</head>
<body></body>
</html>


这种方法的问题是,您很快就会遇到跟踪内容的问题,因此使用其他答案中建议的函数可能是一个好主意。然而,对于小项目来说,这已经足够好了。

你是认真地建议刚开始起步的人应该使用MVC框架吗?我没有看到“起步”这句话,另一方面,这可能是对未来的建议,他现在不必学习,smarty也不难,即使是初学者,我也不知道这些变量是什么,为什么需要它们?你能说得更具体些吗?在PHP中,始终可以使用变量,只需添加它们即可。你的特殊问题是什么?恰恰相反,使用函数会让事情变得模糊,而在同一个模板中,一切都会变得清晰一致。变量如何寻找包括多个外部js/css的变量?