Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup site-wide variables in php?

Tags:

php

I want to define something like this in php:

$EL = "\n<br />\n";

and then use that variable as an "endline" marker all over my site, like this:

echo "Blah blah blah{$EL}";

How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?

like image 252
svec Avatar asked Aug 16 '08 05:08

svec


People also ask

What is $$ variable in PHP?

The $var_name is a normal variable used to store a value. It can store any value like integer, float, char, string etc. On the other hand, the $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name.

Does PHP have global variables?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index].

What is $_ in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>


3 Answers

Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:

 include 'header.php';

you won't have to use the global keyword or anything, the second line of code you wrote should work.

Edit: Oh sorry, that won't work inside functions... now I see your problem.

Edit #2: Ok, take my original advice with the header, but use a define() rather than a variable. Those work inside functions after being included.

like image 182
Paige Ruten Avatar answered Oct 13 '22 21:10

Paige Ruten


Sounds like the job of a constant. See the function define().

like image 24
TT. Avatar answered Oct 13 '22 19:10

TT.


Do this define ('el','\n\<\br/>\n'); save it as el.php

then you can include any files you want to use, i.e

echo 'something'.el; // note I just add el at end of line or in front

Hope this help

NOTE please remove the '\' after < br since I had to put it in or it wont show br tag on the answer...

like image 20
dbwebtek Avatar answered Oct 13 '22 20:10

dbwebtek