nunos
nunos

Reputation: 21409

PHP global keyword workaround

Isn't there another way of using global variables in a Java stlye manner in PHP without the use of the global keyword?

The below example is something very common and simple. I would do it with the define keyword, but as you can see, the varibales are dependent from each other, and I believe you can't achieve that with define.

In the below example I am getting an error, of course.

Really looking forward a solution for this. It just seems to me that having to write a global definition for which funciton I want to use a global variable seems such an ineffective solution that should be a better one.

$BASE_URL = "mysite.com";
$PRODUCTS_URL = $BASE_URL . "/products";
$ABOUT_URL = $BASE_URL . "/about";

function foo() {
    echo $BASE_URL;
}

Upvotes: 2

Views: 1335

Answers (3)

No Results Found
No Results Found

Reputation: 102864

I would do it with the define keyword, but as you can see, the varibales are dependent from each other, and I believe you can't achieve that with define.

Not quite true, this will work just fine - and it's the way I would probably approach this:

define('BASE_URL', "mysite.com");
define('PRODUCTS_URL', BASE_URL . "/products");
define('ABOUT_URL', BASE_URL . "/about");

Just be careful about eating up constant namespace, you might want to write a function instead, maybe something like this (could use tweaking, just an example):

function get_url($item = NULL, $include_base = TRUE)
{
    $urls = array(
        'base'  =>  'mysite.com',
        'products'  =>  '/products',
        'about' =>  '/about',
    );
    $output = $include_base ? $urls['base'] : '';
    if (isset($urls[$item])) $output .= $urls[$item];
    return $output;
}

Then call it like echo get_url('products');. As long as this is defined when foo() is called, it will work. I would always strive to avoid global or $GLOBALS.

Upvotes: 1

Paul Dixon
Paul Dixon

Reputation: 301085

You can use the $GLOBALS superglobal as follows...

function foo() {
    echo $GLOBALS['BASE_URL'];
}

However - see Kolink's comment below. From PHP 5.4.0 the $GLOBALS superglobal is only initialised on first use, so there's a marginal performance advantage in not using it and sticking with the global keyword.

For the kind of thing you're doing, you could simply define a single global array, e.g.

 $CONF['BASE_URL']='foo';

Then you just need use global $CONF in any function that needs it, or better yet, wrap it into some kind of configuration class.

Upvotes: 1

Ervin
Ervin

Reputation: 2452

You could even use $_SESSION but not a very elegant solution. Why is it so hard for you to type global ? It is not big rush.

define() is good as well.

Upvotes: 0

Related Questions