Using Variables in PHP

Just about every programming language uses variables; in fact it's hard to imagine having the capability to perform data processing without variables in some form. Variables are one of the most fundamental structures in programming, and they're usually easy to create and use. You can recognize variables in PHP because they begin with a dollar sign ($). So if you write a dollar sign followed by a name, you have a PHP variable.

Variables do not need to be declared and initialized in PHP, and they don't need a data type set because PHP is what's called a loosely typed language (see the "Strongly Typed and Loosely Typed Languages"). You create a variable simply by including it in an expression, and setting it to a value at the same time. For example, set the $todaysdate variable to the current date value:

$todaysdate = date("m",time()) ."-". date("d",time()) ."-".
 date("Y",time());

Issues Concerning Creating Variables

As you may already know, there are several issues related to variables that are specific to any language that uses them: The issues are:

  • Naming

  • Data Type

  • Scope

Let's discuss each of these issues in more detail.

Naming Variables

Variables are meant to contain data for the purpose of performing data processing operations on it. They are called variables because their data values can vary depending upon what processing has been done to their values.

So a variable really consists of two parts: the variable's name and the variable's value. Because you'll be using variables in your code frequently, it's best to give your variable names you can understand and remember. Like other programming languages, PHP has certain rules you must follow when naming your variables:

  • Variable names begin with a dollar sign ($).

  • The first character after the dollar sign must be a letter or an underscore.

  • The remaining characters in the name may be letters, numbers, or underscores without a fixed limit.

Variable names are case-sensitive ($Variable and $variable are two distinct variables), and names longer than 30 characters are somewhat impractical. In this book we use a few coding conventions that are practical as well as useful, and you'll find adopting a good set of coding conventions is worthwhile. But we'll also mention several of our coding conventions as we talk about variable names.

Here's an example of a variable named in a PHP program:

$my_first_variable = 0;

You might be wondering why this variable is set to a value of zero. In PHP, there's not much point in naming a variable without giving it a value in some way because the act of naming a variable creates it in your program. So while we're creating it, we're also assigning a value of zero to it. Of course, you can create variables and assign any value you like to them, not just zero.

In some languages, you can be restricted (and in some cases prevented entirely) from using a variable without first explicitly declaring (creating) it. But PHP enables you to use variables at any point just by naming them. This is not always the blessing you might think; if you happen to use the same variable name twice by mistake, no error message is generated, and you may end up with a hard-to-find bug. In most cases, though, it works just fine and is a helpful feature.

Data Types

Another consideration when creating a variable is its type or data type. What is a data type, you ask? Data type describes the type of data that a variable holds. If you've ever done any work with databases, you've probably noticed that fields in a database table are often assigned a data type, and that the data type is what distinguishes between strings, numbers, dates, Boolean values, and so on.

The data type of an item determines what kind of processing can be applied to it, as well as how much memory it requires. For example, if you have a data item with a data type of string and a value of 1995, you cannot add it to another string value of 5 and expect to get the number 2000, unless your programming language is especially designed to automatically interpret data types and modify them according to the context in which they are used (fortunately, PHP does just that, but more on that later).

Instead, you'll get a data type error, or perhaps the two strings will be concatenated (joined together into a single string) and your answer would be 19955, not at all what you were expecting.

Strongly Typed and Loosely Typed Languages

In the preceding example, data type rules for a strongly typed language were violated and an error resulted. But PHP is a loosely typed language, and so it saves you from this kind of error by figuring out what you were trying to do and fixing it for you.

The term strongly typed means a language requires explicit declaration of variables types and will generate errors if you try to use operators on them incorrectly, or will give you incorrect answers (not the answer you'd expect) as in the example. Loosely typed languages don't require a declaration of variable type, and automatically convert variable type depending upon the context in which they are used and the operations you perform on their values.

PHP is loosely typed, but enables you to check data type whenever you want to. It also enables you to set and use data types if you want to. Although you don't have to explicitly declare variable and assign a data type, you can determine what data type a variable happens to be at during processing, as well as cast (set) variables to a specific data type as needed.

PHP Data Types

Although PHP is loosely typed, it does support many common simple and structured data types. Simple data types are types that contain a range of values that can be ordered in one dimension (strings, numbers, Booleans, and so on), whereas structured data types include arrays and objects. PHP has eight simple types, which are described in the following table:

Data type

Description

Boolean

Scalar; either True or False

Integer

Scalar; a whole number

Float

Scalar; a number which may have a decimal place

String

Scalar; a series of characters

Array

Compound; an ordered map (contains names mapped to values)

Object

Compound; a type that may contain properties and methods

Resource

Special; contains a reference to an external resource, such as a handler to an open file

NULL

Special; may only contain NULL as a value, meaning the variable; explicitly does not contain any value

Programmers use terms such as scalar, compound, and special to signify characteristics of data types. Scalar signifies that the values the data type holds may be ordered along a scale. For example, numbers are ordered from lower to higher, and characters are ordered in alphabetically. Compound means the data contains multiple data items; for example, arrays contain both index numbers and values associated with them. And special means a special number or value that has a meaning significant to the application, such as a file handler.

Arrays are discussed and full coverage is given to objects (and new object-oriented programming features available in PHP5).

Converting Data Types In PHP

Under ordinary circumstances, you might never need to force the value in a variable from one type to another, but sometimes it helps to be able to do that, such as when you need to make sure you are using a particular type, or when you are preparing output for another program. PHP includes built-in functions for casting (setting) a type.

The PHP function gettype () can be used to determine the current type of a variable, and settype () forces a variable to a particular type. For example, the following code sets the value of a variable as an integer, and then changes it to a string, each time echoing the type. The actual characters that make up the value stay the same, but the data type is changed.

$my_var = 1995; //$my-var is a numeric value
echo "The varaivle is now a ". gettype($my_var) . "<br>";
$my_var = settype($my_var, "string"); //$my_var is now a string
echo "The variable is now a " . gettype($my_var);

The PHP gettype () function returns a string value describing the type it found (such as string, integer, and so on). PHP also contains functions that check for specific types, such as is_string, is_int, and so on. These functions should be used whenever you need to check for a specific type, rather than comparing the gettype () string value returned (for example, integer) to the string you were hoping for (again, integer).

Variable Scope

With the code you've seen so far, you're probably comfortable with the notion that if you create a variable by giving it a name in your code, and then set a value for that variable, you can use it as much as you like, whenever you like, to perform whatever data processing functions you want. That's true to a degree, but there are some limitations. These limitations have to do with scope.

Scope refers to where a variable (actually, the value contained in the variable) may be reached for manipulation. As mentioned, most variables are available anywhere in your PHP program, but when you formally write a function the variables in it are local, meaning they can only be recognized and used within the function. Here's an example of a simple function:

$my_data = "Outside data";
function send_data() {
$my_data = "Inside data";
echo $my_data;
}
send_data(); //sends the inside data to the user
echo $my_data; //sends the outside data to the user

This function just returns data. If the function is called, as in the second-to-last line of code, the output to the user will be Inside data.

However, if the variable $my_data is echoed from outside the function, as shown in the last line of code, Outside data will be sent to the user because $my_data outside the function is not the same as $my_data inside the function, even though both variable names are the same. The scope of $my_data inside the function is said to be local to the function. And by the way, once the function has completed its work, $my_data inside the function is destroyed and its value is lost.

The Global Keyword

Naturally, there is a way to get at outside variables from inside a function. If a variable is declared with the global keyword, it can be accessed from inside a function, as shown in the following example,

$my_data = "Outside data";
function send_data() {
global $my_data;
echo $my_data;
}
send_data(); //sends the outside data to the user
echo $my_data; //also sends the outside data to the user

Static Variables

If you use the keyword static when you create a variable inside a function (meaning the scope of the variable is local to the function, and would ordinarily be lost once the function has run), the variable and its value are preserved between calls to the function. This capability is useful in certain situations in which you'd like to know how many times the function has been called. For example, suppose you wanted to call a function 100 times to return a record from a database, but cause the function to refuse to return records once the value 100 is reached. Specifying a static variable that increments by one each time the function is called would do the trick, as shown here (with a little pseudo code):

function get_record()    {
   static $counter = 0;
   $counter++;
   //check to see if $counter < 100
   //if < 100, run code that gets the record from the database
   //if $counter = or > 100, echo "No more records"
}

This works because each time the function is called, $counter is incremented and the value is still there the next time the function is called.

Defined Constants

You can also define value-containers called constants in PHP. Constants, as their name implies, can be defined (using the define() function) only once in a PHP program, and their value can never be changed nor can they be undefined. They differ from variables in that their names do not start with the dollar sign, but other than that they can be named in the same way variables are.

Constants may only contain scalar values such as Boolean, integer, float, and string (not values such as arrays and objects), can be used from anywhere in your PHP program without regard to variable scope, and are case-sensitive. To define a constant, use the define () function, and include inside the parentheses the name you've chosen for the constant, followed by the value for the constant, as shown here:

define("my_constant", "1995"); //my-constant always has the string value "1995"
echo my_constant; //sends "1995" to the user (note this is not an integer)