Creating PHP Variables

Posted on Jun 26, 2008 by Michael - PHP & MySQL

That’s not a typoPHP lets you create variable variables. A variable variable is one that holds the name of a variable. Here’s how it works: you create a variable named, say, $apples:

<?php
$apples = 4;
.
.
.
?>

Then you can create a new variable, which we’ll name $fruitname, that holds the name of the $apples variable:

<?php
$apples = 4;
$fruitname = "apples";
.
.
.
?>

Now you can refer to the value in $apples as $$fruitname:

<?php
$apples = 4;
$fruitname = "apples";
echo "Number of apples: ", $$fruitname;
?>

This script displays:

Number of apples: 4

You have to be more careful when using double-quotation interpolation, however, because PHP will have trouble with an expression such as $$fruitname in double quotes. To fix that, you use curly braces like this: ${$fruitname}.

Example 1-7, phpvariablevariables.php, shows how this works.

Example 1-7. Using variable variables

<HTML>
<HEAD>
<TITLE>
Using variable variables
</TITLE>
</HEAD>
<BODY>
<H1>
Using variable variables
</H1>
<?php
$apples = 4;
$oranges = 3;
$fruitname = "oranges";
echo "Number of oranges: ${$fruitname} <BR>";
$fruitname = "apples";
echo "Number of apples: ${$fruitname} <BR>";
?>
</BODY>
</HTML>

The results of this example appear in Figure 1-10.

Figure 1-10. Interpolating variable variables.

If you hadn’t used the curly braces in Example 1-7, you would have gotten this result:

Number of oranges: $oranges <BR>
Number of apples: $apples <BR>

Variable variables are important to understand, although they might not look like much more than a curiosity right now. In particular, they’re very useful when you work with loops and arrays, as we’ll be seeing in next Chapter, “Handling Strings and Arrays.

Creating Constants

Sometimes you don’t want variables to be variableyou want their value to be fixed. For example, say you have a variable named $pi that holds the value of pi. It’s possible that such a value may be inadvertently modified, which is not good. The solution is to create a constant, whose value can’t be altered.

You create constants with the define function, giving it the name of the constant and the value you want to assign to it like this: define (”pi“, 3.1415926535);. The name of the constant is always quoted, but the value you assign to the constant is only quoted if it’s a string. Take a look at phpconstants.php in Example 1-8, which creates the constant named pi and displays itnote that when you use the constant, you don’t prefix it with a $. The results of this example appear in Figure 1-11.

Example 1-8. Creating constants

<HTML>
<HEAD>
<TITLE>
Using PHP constants
</TITLE>
</HEAD>
<BODY>
<H1>
Using PHP constants
</H1>
<?php
define ("pi", 3.1415926535);
echo "The constant pi holds " , pi,  "<BR>";
?>
</BODY>
</HTML>

Figure 1-11. Using constants.

If you try to alter the value of this constant (like this: pi = 3.14), PHP won’t accept it and won’t even start the script.

Because you don’t prefix constants with a $, PHP can become confused if you use a constant with the same name as one of the reserved keywords in PHP. These keywords appear in the following list:

PHP Keywords __CLASS__
__FILE__
__FUNCTION__
__LINE__
__METHOD__
and
default
endif
global
print
array
die
endswitch
if
require
as
do
endwhile
include
require_once
break
echo
Eval
include_once
return
case
else
exception
isset
static
cfunction
elseif
Exit
list
switch
class
empty
extends
new
unset
const
enddeclare
For
old_function
use
continue
endfor
foreach
or
while
declare
endforeach
function
php_user_filter
xor

Also, a number of predefined constants are available to your scripts. We’ll use these constants as we need them. Here’s a sample:

__LINE__
The current line number of the file.
__FILE__
The full path and filename of the file.
__FUNCTION__
The function name. (This was added in PHP 4.3.0.)
__CLASS__
The class name. (This was added in PHP 4.3.0.)
__METHOD__
The class method name. (This was added in PHP 5.0.0.)
PHP_VERSION
The PHP version.
PHP_OS
The operating system.
DEFAULT_INCLUDE_PATH

Where PHP will search for what it needs.

For example, using echo __LINE__ at a particular position in a script will display the current line that’s executing.

Handling Data Types

You don’t decide the way your data is stored internallyPHP does. Behind the scenes, it supports eight internal data types (we’ll see all these types in this book):

  • boolean. Holds true/false values
  • integer. Holds numbers such as -1, 0, 5 and so on
  • float. Holds floating-point numbers (”doubles”) such as 3.14159 or 2.7128
  • string. Holds text such as “Hello from PHP.”
  • array. Holds arrays of data items
  • object. Holds programming objects
  • resource. Holds a data resource
  • NULL. Holds a value of NULL

You usually don’t have to worry about these data types because PHP determines a variable’s type based on the kind of data you assign to it. For example, this makes $variable a string:

$variable = "No worries.";

This makes it a float value:

$variable = 1.2345;

This makes it a boolean value:

$variable = TRUE;

Because PHP selects the data type based on the data you assign to a variable, there’s no problem here. The trouble starts when you mix data types by, for example, adding new values to the value in $variable using the + (addition) operator, which we’ll see in next Chapter. Here are some examples:

<?php
$variable = "0";              // $variable is a string set to "0"
$variable = $variable + 2;    // $variable is now an integer set to 2
$variable = $variable + 1.1;  // $variable is now a float set to 3.1
$variable = 2 + "8 apples";   // $variable is now an integer set to 10
?>

If you want to avoid potential data type troubles, don’t mix data types. Even if you do, PHP does the right thing almost every time (such as converting the result of adding an integer and a float into a float value, which is the right thing to do), but if you need to explicitly specify the type of a variable to PHP, you can always use a type cast. Casts appear inside parentheses and come right before the name of the variable whose type you want to specify. Here are a few examples:

$int_variable = (integer) $variable;
$float_variable = (float) $variable;
$string_variable = (string) $variable;

Some hints about mixing data types: when you’re converting to the boolean type, these values are considered FALSE (more on these items, like arrays, is coming up in the book):

  • The boolean FALSE
  • The integer 0
  • The float 0.0
  • The empty string, and the string “0″
  • An array with zero elements
  • An object with no member variables
  • The special type NULL (including unset variables)

Every other value is considered trUE (including any resource). When you’re converting to the integer type:

  • Boolean FALSE will yield 0 (zero), and boolean TRUE will yield 1 (one).
  • Float values will be rounded toward zero.

When you’re converting to the float type, the conversion is the same as if the value was converted to an integer and then to a float. You can also convert from string to the numeric types, but that’s somewhat involvedsee next Chapter for all the details.

In the next chapter, we’re going to start getting control over the data in our PHP scripts by using operators and the PHP statements that control program flow and loopingall vital items for any PHP programmer.