Passing variables to a function within an included file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Excess
Forum Newbie
Posts: 3
Joined: Sat Feb 15, 2003 6:50 pm

Passing variables to a function within an included file

Post 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.
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post 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']);
Excess
Forum Newbie
Posts: 3
Joined: Sat Feb 15, 2003 6:50 pm

Post by Excess »

Hi Stoker,

That works great.

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

Have a great day.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
Post Reply