Thursday, October 9, 2008

PHP - Modify a global variable from within a function

I hope that you find this and i covers what you need, i spent a good few hours trying to work this little bugger out!

So you have a PHP script and every now and again you want to add an ancor link and include 'next', 'previous' and 'top' buttons as the page is generated. Defining a PHP function and just calling it within a loop or at any point would be the easiest method (I think!) but how to send the previous ancor referance?

Marketing aside the following method allows you to do it.

$current_ancor = 1;
//defining the ancor as 1 allows you to go +1 and -1

function latestAncor(){
global $current_ancor;
//get the variable from outside of the function

$next_ancor = $current_ancor+1;
$prev_ancor = $current_ancor-1;

$line = '<a name="ancor_number_'.$current_ancor.'"></a>
<a href="#top">Top button</a>
<a href="#ancor_number_'.$prev_ancor.'">Previous</a>
<a href="#ancor_number_'.$next_ancor.'">Next</a>';

$GLOBALS["current_ancor"] = $current_ancor;
//this updates the current_ancor variable outside of the function
//with the next ancor number
return $line;

Call the function whereever you like using <? echo latestAncor();?>
Modify and adapt how you wish but this worked perfectly for me...

NOTE: You may need to ensure that register globals is set to on or off in your PHP?

No comments: