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;
}
Not quite true, this will work just fine – and it’s the way I would probably approach this:
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):
Then call it like
echo get_url('products');. As long as this is defined whenfoo()is called, it will work. I would always strive to avoidglobalor$GLOBALS.