Page 1 of 1

How to use a function? - SOLVED

Posted: Sat Nov 11, 2006 3:31 am
by matth2004
Hi,

I have created a function like this:

Code: Select all

function SetHTML() {

$pagetop = "hello this is a title $temptitle goodbye";
$pagebottom = "this is the bottom $temptitle goodbye";
};

And I want to know how to call on it properly. I currently get the $temptitle variable from a MySQL database which has the title of the page. I then call on it so that it can set the variables correctly and the function puts the title that I have already got into the variable for me. When I go to echo $pagetop and $pagebottom outside of the function they are blank. Why is this? Is there something I'm doing wrong?

Thanks in advance,
Matt

Posted: Sat Nov 11, 2006 3:52 am
by s.dot
You need a return value. Perhaps something like this:

Code: Select all

function SetHTML() { 

$pagetop = "hello this is a title $temptitle goodbye"; 
$pagebottom = "this is the bottom $temptitle goodbye"; 

return array('pagetop' => $pagetop, 'pagebottom' => $pagebottom);

}
Then you can assign the function result to a variable.

Code: Select all

$pageinfo = SetHTML();
Then you can use info that that function returned..

Code: Select all

echo $pageinfo['pagetop'];

//

echo $pageinfo['pagebottom'];

Also, you included a ; at the end of your function. Not needed (might be a parse error, not sure).

Posted: Sat Nov 11, 2006 3:59 am
by timvw
Simply read http://be2.php.net/manual/en/language.v ... .scope.php and you'll feel enlightened :)

Posted: Sat Nov 11, 2006 4:09 am
by matth2004
Thanks heaps for your replies and the globals variable worked perfectly! Never would of though of that.

Thanks again,
Matt

Posted: Sat Nov 11, 2006 3:51 pm
by John Cartwright
Use the return keyword instead of globals, globals will only result in horrible code smell and unpredictable behavior.