Include has the scope of the line it's called from.
If you don't want to create new global variables, you can wrap include()
with a function:
function includeHeader($title) {
include("inc/header.php");
}
$title
will be defined in the included code whenever you call includeHeader
with a value, for example includeHeader('My Fancy Title')
.
If you want to pass more than one variable you can always pass an array instead of a string.
Let's create a generic function:
function includeFile($file, $variables) {
include($file);
}
Voila!
Using extract makes it even neater:
function includeFileWithVariables($fileName, $variables) {
extract($variables);
include($fileName);
}
Now you can do:
includeFileWithVariables("header.php", array(
'keywords'=> "Potato, Tomato, Toothpaste",
'title'=> "Hello World"
));
Knowing that it will cause variables $keywords
and $title
to be defined in the scope of the included code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…