Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

php - How to pass arguments to an included file?

I'm trying to make the whole <head> section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.

So here is the code:

index.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.

header.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>

Obviously this doesn't work; how can I pass arguments to an included file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...