Page 1 of 1

Passing variables to a function within an included file

Posted: Mon Feb 17, 2003 11:41 am
by Excess
Hello Dear People,

Having searched for hours on the forum, I am tearing my hair out. Please help.

My issue is that I am trying to pass a variable to an function defined in an included script.

My function is GenerateHeader() that is defined in the file common.php.

GenerateHeader() contains html for my site logo and menu bar.

The main page for my site, home.php is fed the value of $key from the URL. Home.php includes common.php to generate the top half of the page.

Is there any way to pass $key to the GenerateHeader() function in the included common.php?

Here is some code to illustrate.
home.php -- $key is given a value from the URL ie: home.php?key=value

Code: Select all

<?
include("common.php");
GenerateHeader();
?>
<html>
<head>
</head>
<body>
//HTML for the page content.
<?=$key?>
</body>
</html>
This is the function in common.php - I would like the value of $key to be appended to the end of each link because the scripts (page2.php, page3.php, etc) will use $key in forms and things like that.

Code: Select all

function GenerateHeader() &#123;
?>
<html>
<head>
</head>
<body>
//html for menu bar and top bar ie:
<a href="page2.php?key=<?=$key?>">Page 2</a>
<a href="page3.php?key=<?=$key?>">Page 3</a>
</body>
</html>
I really hope someone can help me.
Thanks in advance.

Posted: Mon Feb 17, 2003 12:16 pm
by Stoker
In the function just add the vars you want passed..

# The function
function myfunction ($myvar) {
# do stuff and you can use $myvar at will
}

# The call
myfunction ('This is my passed value');

or in your case more like
GenerateHeader($_REQUEST['key']);

Posted: Mon Feb 17, 2003 12:25 pm
by Excess
Hi Stoker,

That works great.

Thankyou so much for the quick (and correct :wink:) reply.

Have a great day.

Posted: Tue Feb 18, 2003 2:14 am
by twigletmac
Or if the variable is always going to be called key and come from the URL you can just do:

Code: Select all

<?php
function GenerateHeader() { 
    $key = $_GET['key'];
?> 
<html> 
<head> 
</head> 
<body> 
//html for menu bar and top bar ie: 
<a href="page2.php?key=<?=$key?>">Page 2</a> 
<a href="page3.php?key=<?=$key?>">Page 3</a> 
</body> 
</html>
No matter which method you go for, you should check that the key exists (isset() or empty()) and is in a form you expect (e.g. is_numeric()).

Mac