Learning Objectives – after this chapter you will be able to:
- Define constants with
define()andconst. - Create variables, follow the naming rules and understand loose typing.
- Use PHP's data types and inspect them with
var_dump()andgettype(). - Explain local, global and static variable scope.
- Know the superglobal arrays
$_GET,$_POST,$_SESSION,$_COOKIE,$_REQUEST,$_SERVER,$_FILESand$_ENV.
Constants
A constant is a name (placeholder) for a value that does not change while the script runs. Constants are usually written in CAPITAL letters so that they are easy to find in the code. A constant name must begin with a letter or an underscore – never with a number – and constant names are case-sensitive. Constants are not prefixed with $.
You define a constant with the function define(). Once defined, a constant cannot be changed or undefined.
define("CONSTANT_NAME", value);
const CONSTANT_NAME = value; // compile-time alternative (also used in classes)<?php
define("SUBJECT", "PHP/MySQLi");
const INSTITUTE = "Bhopal";
echo "We all are learning: " . SUBJECT . "<br>";
echo "Batch at " . INSTITUTE . "<br>";
echo "Is SUBJECT defined? " . (defined("SUBJECT") ? "Yes" : "No") . "<br>";
echo "PHP_VERSION is a built-in constant: " . PHP_VERSION . "<br>";
echo "PHP_INT_MAX = " . PHP_INT_MAX;
?>We all are learning: PHP/MySQLi Batch at Bhopal Is SUBJECT defined? Yes PHP_VERSION is a built-in constant: 8.3.6 PHP_INT_MAX = 9223372036854775807
Trying to define the same constant again produces a warning "Constant SUBJECT already defined", and the old value is kept. In PHP 8 the third argument of define() (case-insensitive constants) is no longer supported.
Variables
Variables store values – text strings, numbers or arrays. Once a variable is declared it can be used again and again in the script. All variables in PHP start with a $ sign.
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable – then it does not work. Let us create a variable containing a string and a variable containing a number:
<?php $txt = "Hello World!"; $x = 16; $price = 99.50; echo $txt . "<br>"; echo "x = $x and price = $price<br>"; $x = $x + 4; // a variable can be changed echo "Now x = $x"; ?>
Hello World! x = 16 and price = 99.5 Now x = 20
PHP is a loosely typed language
In PHP a variable does not need to be declared before a value is assigned to it, and you do not tell PHP which data type it has. PHP automatically gives the variable the correct data type, depending on its value. In a strongly typed language (C, Java) you must declare the type and the name of a variable before using it.
Naming rules for variables
- A variable name must start with a letter or an underscore
_(after the$). - A variable name may contain only letters, numbers and underscores (a–z, A–Z, 0–9, _).
- A variable name must not contain spaces. Write multi-word names as
$my_stringor$myString. - Variable names are case-sensitive:
$Employeeand$employeeare different variables.
Data Types
| Type | Holds | Example |
|---|---|---|
| int (integer) | Whole numbers | $age = 25; |
| float (double) | Real numbers with a decimal point | $pi = 3.14; |
| string | A sequence of characters (text) | $name = "Asha"; |
| bool (boolean) | true or false | $paid = true; |
| array | A set of values under one name | $a = [1, 2, 3]; |
| object | An instance of a class | $d = new DateTime(); |
| null | "No value" | $x = null; |
| resource | A handle to an external resource | $f = fopen("a.txt","r"); |
var_dump() shows the type and the value of a variable; gettype() returns the type name as a string.
<?php
$i = 42;
$f = 3.75;
$s = "PHP";
$b = true;
$a = array("red", "green");
$n = null;
echo "<pre>";
var_dump($i);
var_dump($f);
var_dump($s);
var_dump($b);
var_dump($a);
var_dump($n);
echo "gettype(\$f) = " . gettype($f) . "\n";
echo "</pre>";
?>int(42)
float(3.75)
string(3) "PHP"
bool(true)
array(2) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
}
NULL
gettype($f) = doubleType juggling and casting
Because PHP is loosely typed, it converts values automatically when needed ("type juggling"). You can also convert explicitly with a cast – (int), (float), (string), (bool), (array).
<?php $a = "10"; // a string $b = 5; // an integer $c = $a + $b; // string "10" is converted to a number echo "\"10\" + 5 = $c (type " . gettype($c) . ")<br>"; echo "\"10\" . 5 = " . ($a . $b) . "<br>"; // . joins strings echo "(int) 12.9 = " . (int) 12.9 . "<br>"; echo "(float) \"3.5kg\" = " . (float) "3.5kg" . "<br>"; echo "(bool) 0 is "; var_dump((bool) 0); echo "<br>(bool) \"hello\" is "; var_dump((bool) "hello"); ?>
"10" + 5 = 15 (type integer) "10" . 5 = 105 (int) 12.9 = 12 (float) "3.5kg" = 3.5 (bool) 0 is bool(false) (bool) "hello" is bool(true)
Variable Scope
The scope of a variable is the part of the script in which it can be used. In most cases variables are local: a variable declared inside a function cannot be accessed outside the function, and a variable declared outside a function cannot be accessed inside it. To use a global variable inside a function you must declare it global or access it through the $GLOBALS array.
<?php
$site = "phpbook"; // global scope
function showLocal() {
$msg = "inside"; // local scope
echo "Local msg: $msg<br>";
echo "Global site without 'global': " . @$site . "(empty)<br>";
}
function showGlobal() {
global $site; // bring the global variable into the function
echo "With global keyword: $site<br>";
echo "With \$GLOBALS array: " . $GLOBALS['site'] . "<br>";
}
function counter() {
static $count = 0; // keeps its value between calls
$count++;
echo "counter() called $count time(s)<br>";
}
showLocal();
showGlobal();
counter(); counter(); counter();
?>Local msg: inside Global site without 'global': (empty) With global keyword: phpbook With $GLOBALS array: phpbook counter() called 1 time(s) counter() called 2 time(s) counter() called 3 time(s)
- A static variable inside a function keeps its value between calls, instead of being reset each time.
- The
@operator used above suppresses the warning for the undefined local$site; normally you should not hide errors this way.
register_globals (historical)
Older PHP books mention the php.ini setting register_globals. When it was on, every form field, cookie and URL parameter automatically became a normal variable – ?name=Asha created $name. This allowed attackers to inject values into variables, so the default was switched to off in PHP 4.2, it was deprecated in 5.3 and removed in PHP 5.4. Modern PHP never creates variables from request data automatically; you always read them from the superglobal arrays below.
Superglobals – Variables Passed Between Pages
Superglobals are built-in arrays that are available in every scope – inside and outside functions – without the global keyword.
| Superglobal | Contains |
|---|---|
| $_GET['name'] | Values sent in the URL / by a form with method="get". |
| $_POST['name'] | Values sent by a form with method="post". |
| $_REQUEST['name'] | Contents of $_GET, $_POST and $_COOKIE together – use when it does not matter how the value was sent. |
| $_SESSION['name'] | Values stored in the current session (Chapter 31). |
| $_COOKIE['name'] | Values of cookies sent by the browser (Chapter 30). |
| $_SERVER['name'] | Information from the web server – headers, paths, script location. |
| $_FILES['name'] | Information about uploaded files (Chapter 14). |
| $_ENV['name'] | Variables from the operating-system environment. |
| $GLOBALS['name'] | All variables of the global scope. |
<?php echo "Script name : " . $_SERVER['PHP_SELF'] . "<br>"; echo "Request method : " . $_SERVER['REQUEST_METHOD'] . "<br>"; echo "Query string : " . $_SERVER['QUERY_STRING'] . "<br>"; echo "City from \$_GET : " . $_GET['city'] . "<br>"; echo "PIN from \$_REQUEST : " . $_REQUEST['pin'] . "<br>"; echo "Server name : " . $_SERVER['SERVER_NAME']; ?>
Script name : /phpbook/ch04/server.php Request method : GET Query string : city=Bhopal&pin=462011 City from $_GET : Bhopal PIN from $_REQUEST : 462011 Server name : localhost
Key Takeaways
- Constants are defined with
define()orconst, have no$and cannot be changed. - Variables start with
$, need no declaration and get their type from the assigned value. - Variable names start with a letter or underscore and are case-sensitive.
- PHP types: int, float, string, bool, array, object, null and resource; use
var_dump()to inspect them. - Variables are local to functions; use
global,$GLOBALSorstaticwhen needed. register_globalswas removed in PHP 5.4; read request data from$_GET,$_POST,$_REQUESTand the other superglobals.
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch04 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – Constants. https://www.php.net/manual/en/language.constants.php
- The PHP Group. (n.d.). PHP Manual – Variables. https://www.php.net/manual/en/language.variables.php
- The PHP Group. (n.d.). PHP Manual – Types. https://www.php.net/manual/en/language.types.php
- The PHP Group. (n.d.). PHP Manual – Variable scope. https://www.php.net/manual/en/language.variables.scope.php
- The PHP Group. (n.d.). PHP Manual – Superglobals. https://www.php.net/manual/en/language.variables.superglobals.php