Forum Moderators: coopster

Message Too Old, No Replies

Set static value throughout site

Was easy in ASP, please help me in PHP!

         

bateman_ap

12:02 pm on Jan 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have come across a bit of a problem in PHP, my background was classic ASP and have decided to learn a bit of PHP as .net just confuses me too much!

What I am trying to do is set a "API Key" that is used throughout the site. I have a "functions.php" file that is included on every page that I thought I could just set the key in, however it doesn't seem to work. At the moment I have:


$apikey= '123456789';

at the top of my functions.php, I am then trying to use it in a function as shown below:

function writeWidget($widgetid)
$param = array(
'apikey' => $apikey,
'widgetid' => $widgetid
);
.....

However when I run it I get:

Notice: Undefined variable: apikey

If I hardcode it in the functino it works perfectly, any ideas, I must be being stupid!

tomda

12:10 pm on Jan 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The variable $apikey is not defined...

Just call it as a global variable within the function

function writeWidget($widgetid) {
global $apikey;
$param = array(
'apikey' => $apikey,
'widgetid' => $widgetid
);
.....}

bateman_ap

12:17 pm on Jan 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Many thanks, worked perfectly. Out of interest why do you have to define it in every funciton?

tomda

12:30 pm on Jan 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



PHP.net says
In PHP global variables must be declared global inside a function if they are going to be used in that function.

[php.net...]

penders

12:47 pm on Jan 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If you don't declare it global in the function, then another variable (of the same name) will be created local to that function.

Alternatively you could refer to the $GLOBALS[] array in order to access your global variable. This is a superglobal and can therefore be accessed directly in any scope.

function writeWidget($widgetid) { 
$param = array(
'apikey' => $GLOBALS['apikey'],
'widgetid' => $widgetid
);
}

Or, you could define() a constant (if apikey is constant?) instead of using a global variable. Constants can also be accessed in any scope (but cannot obviously be changed)...

define('APIKEY','123456789'); 
function writeWidget($widgetid) {
$param = array(
'apikey' => APIKEY,
'widgetid' => $widgetid
);
}

"By convention, constant identifiers are always uppercase." (Constants - PHP Manual [uk.php.net])