Understanding Variables and Constant in PHP

”;$bool = false;print “Bool is set to” ;print (int) $bool;This time the script output 1 and 0 as we wanted.

PHP will automatically convert data types as necessary, you need not to worry about it happening.

However, you can typecast and type of variable into any other type, like this:$mystring = “wombat”;$myinteger = (integer)$mystring;At first, $mystring contains a string.

However, we typecast it to be an integer, so PHP will convert it to an integer and place the result into $myinteger.

You can typecast as boolean using (bool), string using (string), and floating-point using (float).

Typecasting is most often used to specifically enforce a type to provide extra security or to ensure a set type of data is being used.

For example, if your script absolutely requires an integer number, it’s a smart move to typecast your variable with integer so that PHP will convert any other type to integer or do nothing if the type is already an integer.

Converting a float to an integer will round the number down to the nearest whole number, and is actually faster than using the equivalent rounding function.

VARIABLE SCOPEEach variable has a life span in which it exists, known as its scope.

It is technically possible for a PHP script to have several variables called $a in existence at one point in time, however, there can only be one active $a at any one time.

Any variable not set inside a function or an object are considered global, that is, they are accessible from anywhere else in the script, except inside another function or an object.

We will talk about variable scope later in this article.

VARIABLE’S VARIABLESVariables Variables are somewhat complicated to use, and even more complicated to explain, so you might need to reread this section a few times before it makes sense.Variable variables allow you to access the contents of a variable without knowing its name directly — it is like indirectly referring to a variable.

Here is an example:$bar = 10;$foo = “bar”;From that point, there are two ways we can output the value of $bar: we can either use print $bar, which is quite straightforward, or we can take advantage of the concept of variable variables and use print $$foo;By using $$foo, PHP will look up the contents of $foo, convert it to a string, then look up the variable of the same name and return its value.

In the example above, $foo contains the string “bar”, so PHP will look up the variable named $bar and output its value, in this case, 10.

It is possible to use as much indirection as you want, giving variables like $$$foo and $$$$$$bar.

That said, anything beyond one level of indirection can lead to very subtle bugs, and so is best avoided.

Variable variables are often used to choose between two values dynamically so that the output part of a script reference $var but another part of the script actually sets what $var points to.

For example, if you have calculated the temperature in Fahrenheit and Celsius and want to choose only one to print out, you might use this code.

$temperature_f = 59;$temperature_c = 15;$units = “temperature_f”;$t = $$units;That assigns the value of $temperature_f to $t.

Variable variables can be helpful from time to time but are clumsy to use.

Furthermore, they only get more clumsy the more indirection you use.

For example, the next script outputs “variable!” four times, but I hope you agree it is not very easy to read:$foo = “variable.”;$bar = “foo”;$wom = “bar”;$bat = “wom”;Print $foo;Print $$bar;Print $$$wom;Print $$$$bat;SUPERGLOBALS IN PHPVariables that come into PHP arrive inside one of several arrays known collectively as the supergoals, so named because they are available throughout your script, even inside objects and other arrays.

Superglobals include form data sent from your visitor, cookie data, session information, local server information and more, making them good to keep around.

Superglobals were not available in PHP, but there were older alternatives that provided much of the functionality.

Superglobals are superior, though, so it is recommended that all new scripts use them.

Here are some of the superglobal arrays, which are available for us:$_GET: contains all variables sent via a HTTP GET request.

$_POST: Contains all variables sent via a HTTP POST request.

This is similar to the old $HTTP_POST_VARS array, which, although deprecated, is still available for use.

$_FILES: contains all variables sent via HTTP cookies$_REQUEST: Contains all variables sent via HTTP GET, HTTP POST, and HTTP cookies.

Many programmers still use the old syntax for these variables, so you may wonder why they are deprecated.

There are two differences between the old versions and the new versions:1.

The new versions are much shorter to type.

Most people would rather type $_GET than $HTTP_GET_VARS each time they want to access a variable.


The new versions are automatically global everywhere in your script, even inside a function.

The older variables were not available inside functions unless you specifically requested for them to be available.

There are two superglobal arrays that you should avoid unless you particularly need them, namely, $GLOBALS and $_REQUEST.

Both of these arrays are combinations of the other arrays and may include untrusted user data.

When you use $_COKIE[‘somevar’], you know that the value has come from a cookie on the user’s machine, and not from someone editing your site’s URL.

When using $_REQUEST[‘somvar’], you no longer have that guarantee, and you are left wholly trusting the user.

Of course, it is also possible that a user has edited the cookie on her machine, so place no more trust in $_COOKIE data than you have to.

Scripts are written before Superglobals were available need to be converted to use them.

If you would rather not convert the script — either because you need the backward compatibility with very old PHP versions or you simply don’t have the time — then you have two options:1.

Enables register_globals in your php.

ini file.

This will revert PHP back to its insecure, pre-4.

1 functionality-the superglobals will still be there, but all input will be automatically converted into variables.


Use the function import_request_variables() to extract a given superglobal’s content into normal variables.

One important thing to note is that $GLOBALS always contains itself too, which means that if you try to cycle through each variable in $GLOBALS in some older versions of PHP, you will enter into a recursive loop.

Modern PHP releases detect array recursion and print the message “RECURSION” when $GLOBALS tries to print itself.

USING $_ENV AND $_SERVERBefore you get control in your script, PHP sets several variables for you containing information about the server, the environment, and your visitor’s request.

These are stored in the superglobal arrays $_ENV and $_SERVER, but their availability depends on whether the script is being run through a web server or on the command line.

The most commonly used $_SERVER variables are HTTP_REFERER, HTTP_USER_AGENT, PATH_INFO, PHP_SELF.

Of those, HTTP_REFERER and HTTP_USER_AGENT are the most important, as you can use these two to find out a lot about your visitor and then take the appropriate action.

For example:<?phpif (isset($_SERVER[‘HTTP_REFERER’])) {print “the page you were on previously was {$_SERVER[‘HTTP_REFERER’]}<br />”} else {print “You didn’t click any links to get here <br />”}?><a href=”refer.

php”> Click me.</a>>If you load that page in your browser by typing the URL in by hand, the “You didn’t click any links to get here” text is shown because HTTP_REFERER has not been set.

However, if once the page is loaded you follow the “Click me!” link, the page will reload itself, this time, HTTP_REFERER will be set and the other message should appear.

Although it can be easily spoofed, HTTP_REFERER is generally a good way to make sure a visitor came from a certain page-whether you want to use that to say, “You can’t download my files because you came from another site” or “Welcome, Google user!” is up to you.

The PATH_INFO element in $_SERVER is particularly interesting because it allows you to grab directory information specified after the script.

Consider this script:<?phpif (isset($_SERVER[‘PATH_INFO’])) {print “The page you requested was {$_SERVER[‘PATH_INFO’]}<br />”} else {print “You didn’t request a page <br />”}?>Save that doe as pathinfo.

php, then load it in your web browser.

You will see you didn’t request a page.

Edit the URL, adding a filename onto the end of pathinfo.


For example, www.





Now when you load the page, you should see that extra path information printed out.

This is commonly used in the online filesystem, as it means that the URL required to get to a file is just the name of the script followed by the filename wanted.

The $_ENV variables contain environment variables in your system.

On Windows, this usually includes variables like “OS”, “WINDIR”, and so on.

If you are using PHP on the command line, the $_SERVER superglobal will include all the variables from $_NEW.

CONSTANTS IN PHPIf you find yourself setting a variable for convenience and never changing it during a script, chances are you should be using a constant.

Constants are like variables except that once they are defined, they cannot be undefined or changed — they are constant, as the name suggests.

Unlike many other languages, constants are not faster than variables in PHP.

The primary advantages to using the constants are the fact that they do not have a dollar sign at the front and, therefore are visibly different from variables.

Furthermore, constants are automatically global across your entire scripts, unlike variables.

To set a constant, use the define() functions.

It takes two parameters, the first being the name of the constant to set, and the second being the value to set.

For example, the following line of code sets the constant SecondsPerDay, then prints it out.

define(“SecondsPerDay”, 86400);print SecondsPerDay;Note that it is not $SecondsPerDay or SECONDSPERDAY — the names of constants, like the name of variables, are case-sensitive — but unlike variables, they do not start with a dollar sign.

You can change this behaviour by passing true as a third parameter to define(), which makes the constant case-insensitive:define(“SecondsPerDay”, 86400, true);print SecondsPerDay;print SecondsPerDay;There are two helpful functions available for working with constants, and these are defined() and constant().

The defined() functions is basically the constant equivelent of isset(), as it returns true if the constant string you pass to it has been defined.

For example:define(“SecondsPerDay”, 86400, true);if(defined(“SecondsPerDay”)) {//etc}Note that you should pass the constant name into defined() inside quotes.

Finally, constant() is a function that at first seems redundant, but is important nonetheless, it returns the value of a constant.

While you can get the value of a constant just by using it.

PRESET CONSTANT IN PHPThere are a number of constants automatically set by PHP in order to save you having to recalculate complicated values each time in your script, but PHP also provides other helpful information.

For example, PHP always set the __FILE__, __LINE__, __FUNCTIONS__, __CLASS__ AND __METHOD___ constants for you — note that there are double underscores on either side to make it unlikely you will use these names for your own constants.

Using these special constants, it is very easy to output complex error reports or other debugging information.

PHP defines numerous constant for use in its functions and extensions — a great many of these are outlines elsewhere in this article, and they help you remember values.

There are some generic coding constant that you might find useful, such as PHP_EOL to grab the newline character for the current OS, PHP_OS to grab the name of the OS, PHP_VERSION to get the version number of the engine, and DEFAULT_INCLUDE_PATH to see where PHP will include files from, if it can’t find them in the local directory.


. More details

Leave a Reply