AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

php super globals, how to use them

small question, is it better to do

$HOST = $_SERVER["HTTP_HOST"];

and use $HOST throughout my web application

OR

is it better to do

define ( "HOST", $_SERVER["HTTP_HOST"] );

and use HOST throughout my entire web application

OR

is it better to forget using variables and constants and just use $_SERVER["HTTP_HOST"]; every time I need the host?

Which ways more efficient. Which ways more readable.

Which way should I use?

Upvotes: 1

Views: 281

Answers (4)

pp19dd
pp19dd

Reputation: 3633

Better is a relative term. Using $_SERVER["HTTP_HOST"] is perfectly acceptable, since everyone looking at it instinctively knows what it's supposed to be and not have to guess if that contains a complete URL or otherwise.

Even if you have to spoof a production hostname for testing, you can still do so with $_SERVER['HTTP_HOST'] = 'www.mywebsite.whatever';

Upvotes: 0

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34591

Global state is normally bad, since it couples components, breaking the IoC concept.

I would use dependency injection to pass parameters between classes and modules.

But if you really want to use a global variable, why don't you just use $_SERVER["HTTP_HOST"]?

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

The less global variables you have the better, IMHO so just use $_SERVER["HTTP_HOST"] in all of your application. If you really want to define it

define ( "HOST", $_SERVER["HTTP_HOST"] );

is the way to go

Upvotes: 2

GoSmash
GoSmash

Reputation: 1108

Its better for you use second one,

define ( "HOST", $_SERVER["HTTP_HOST"] );

define it and use it anywhere..

Don't go for third one at any case, because hard coding will affect a lot in future.

Upvotes: 2

Related Questions