目前,我使用include的方式是为其他页面带来页眉、页脚和一些内容。
这会导致更多的包含,而不是我真正想要的,因为我需要为包含添加更多的内容。
例如:<!DOCTYPE html>
<?php include('header.php'); ?>
<body>
<?php include('body-top.php');
custom html
</?php include('footer.php');
</body>
如果我能在包含和我想要包含显示的页面上添加变量,那就太好了。
我根本不擅长PHP,所以有没有更好的方法来使用include ?
这很容易做到:
index . php
$title = 'Hello World!';
include 'content.php';
content.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body></body>
</html>
这种方法的问题是,您很快就会遇到跟踪内容到哪里的问题,因此按照其他答案中建议的使用函数可能是一个好主意。然而,对于小项目来说,我认为这已经足够好了。
听起来像是Smarty的工作
看起来是这样的
<?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>
或者更好的方法,使用一些PHP MVC框架,它会给你更多的东西(不仅仅是模板系统)
你的include已经很少了,不需要再优化了
也不要注意那些建议使用Smarty或MVC的人,因为那样会大大增加包含的数量(当然是为了换取其他好处)——
您可以将包含的文件转换为函数。PHP有一个巧妙的技巧,在花括号之间(即{
和}
)的任何内容只在到达该部分代码时才执行。这包括PHP标记之外的HTML代码。
这可能是我们的'header.php'文件,我们将当前代码包装在一个函数中。
<?php function doHeader($title) { ?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<?php } ?>
然后我们为它做一个测试器。无论我们的测试者/调用者选择作为$title
传递什么,都会显示在我们的输出中。
<?php
// All included here
include_once('header.php');
?><!DOCTYPE html>
<?php doHeader('My page title'); ?>
<body></body>
</html>
这会产生输出,
<!DOCTYPE html>
<html>
<head>
<title>My page title</title>
</head>
<body></body>
</html>