PHP - Chapter 4 - Variables

Introduction

The more useful applications require the use of variables. As in mathematics, a variable is a placeholder for a value. PHP variables are always led with a dollar sign, as in $variableName. In PHP, variables are case sensitive, this means that the variable $foo is different than $FOO. Variable names can contain letters, numbers, and underscores; but, they cannot begin with a number or underscore.

In order to display the value of a variable, you once again make use of the echo() command. The only difference is that you are not required to use quotation marks within the parenthesis. The use of quotation marks implies a string literal. This means that everything within the quotations are interpretted exactly as typed. When you store a string to a variable, you pass the string as a string literal. Variables can contain numerical values and can be mathematically manipulated as well.

Definitions (in layman's terms)

Variable: A placeholder for a specified or calculated value.

String Literal: Textual information that is interpretted exactly as typed in its surrounding quotation marks.

Escape Character: A reserved character preceeded by a backslash (\) that issues special commands to the PHP interpreter.

Code:
<html>
<head>
	<title>Variables in PHP</title>
</head>
<body>
	<?php
		$stringVar = "<p>This is a string variable</p>\n";
		$numVar = 2;
		$floatVar = 3.3;

		// This prints the value of stringVar to the screen
		echo($stringVar);

		$foo = $numVar * $floatVar;	// This means foo = 6.6

		echo("<p>numVar = $numVar<br />floatVar = $floatVar</p>\n");
		echo("<p>$numVar * $floatVar = $foo</p>\n");
	?>
</body>
</html>
Breakdown

This script makes use of all that you have learned thus far. First, the string literal, "<p>This is a string variable</p>\n" is stored in the variable container, stringVar. You already know that the tags <p> and </p> are X/HTML tags that are interpreted by the browser, the \n is called an escape character. \n is the escape character that tells the PHP server to insert a line-feed or carriage-return into the stream.

Next in the script, the values 2 and 3.3 are stored in the variable containers numVar and floatVar, respectively. Using the echo() command, the PHP server outputs the value of stringVar to the screen. Then, the product of numVar and floatVar is stored in the variable container, foo.

Using the echo() command, the strings "<p>numVar = $numVar<br />floatVar = $floatVar</p>\n" and "<p>$numVar * $floatVar = $foo</p>\n" are printed to the screen with the values of numVar and floatVar and foo are substituted into their placeholders within the strings.

Note: there are specific variables that are reserved by PHP. Most of these are seen using script01.php. The phpInfo() function outputs a section near the bottom called "GLOBAL" variables. These are reserved by PHP and will be address further later.

< Back - Comments PHP Index Next - Comments >