Welcome to WebmasterWorld Guest from 54.157.222.62

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Global variable between php includes

   
1:37 am on Oct 20, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi All,

I'm trying to declare a variable to be used across a few includes that make up a page.

In my functions.php file I have the following code, which grabs the current URI and creates a keyword out of it:

functions.php
global $COUNTRY_NAME;
$file_path = $_SERVER['REQUEST_URI'];
$parts = Explode('/', $file_path);
$keyword = $parts[count($parts) - 1];
$keyword = str_replace("-", " ", $keyword);
$keyword = ucwords($keyword);
$COUNTRY_NAME == $keyword;
return $COUNTRY_NAME;


in my page.php

<?php
global $COUNTRY_NAME;
echo $COUNTRY_NAME;
?>

And of course...$COUNTRY_NAME seems to be blank.

This is within a wordpress theme, btw.

Any ideas? I'm very novice at this, and I'm sure I have a $ sign in the wrong place or something :)
5:40 am on Oct 20, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$COUNTRY_NAME == $keyword;


Should be

$COUNTRY_NAME = $keyword;

Mistakenly there are two "=" signs there
4:49 pm on Oct 20, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Variables declared previously should always be available to subsequent includes and parent files (with exceptions.) You don't need the global keyword in the context you've described it.

functions.php:
<?php
$COUNTRY_NAME='Foo';
?>

page.php:
<?php
include('functions.php');
echo $COUNTRY_NAME;
?>

Should be fine. However, since you're using the names functions.php and page.php, the first good guess is that this is Wordpress, and if not, that functions.php should contain actual functions, in which case "global" or something like it becomes very important.

This will not work.

functions.php:
<?php
function get_country() {
$COUNTRY_NAME='Foo';
}
?>

page.php:
<?php
include('functions.php');
get_country();
echo $COUNTRY_NAME;
?>

The reason being, $COUNTRY_NAME is local to the function get_country. You could patch it by assigning it as a global:


<?php
function get_country() {
global $COUNTRY_NAME;
$COUNTRY_NAME='Foo';
}
?>

Which would work, but look at this. You don't need to, and makes your function more object-like (though it's not exactly an object, it's independent and doesn't rely on globals to work.)

functions.php:
<?php
function get_country() {
$COUNTRY_NAME='Foo';
return $COUNTRY_NAME;
}
?>

page.php:
<?php
include('functions.php');
echo get_country();
?>

If you really, really need to use globals (which you rarely should) use constants instead.