13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

30 Chapter 1 <strong>PHP</strong> Crash Course<br />

This ability to change types transparently on the fly can be extremely useful.<br />

Remember <strong>PHP</strong> “automagically” knows what data type you put into your variable. It<br />

returns the data with the same data type when you retrieve it from the variable.<br />

Type Casting<br />

You can pretend that a variable or value is of a different type by using a type cast.This<br />

feature works identically to the way it works in C.You simply put the temporary type in<br />

parentheses in front of the variable you want to cast.<br />

For example, you could have declared the two variables from the preceding section<br />

using a cast:<br />

$totalqty = 0;<br />

$totalamount = (float)$totalqty;<br />

The second line means “Take the value stored in $totalqty, interpret it as a float, <strong>and</strong><br />

store it in $totalamount.”The $totalamount variable will be of type float.The cast<br />

variable does not change types, so $totalqty remains of type integer.<br />

You can also use the built-in function to test <strong>and</strong> set type, which you will learn about<br />

later in this chapter.<br />

Variable Variables<br />

<strong>PHP</strong> provides one other type of variable: the variable variable.Variable variables enable<br />

you to change the name of a variable dynamically.<br />

As you can see, <strong>PHP</strong> allows a lot of freedom in this area. All languages enable you to<br />

change the value of a variable, but not many allow you to change the variable’s type, <strong>and</strong><br />

even fewer allow you to change the variable’s name.<br />

A variable variable works by using the value of one variable as the name of another.<br />

For example, you could set<br />

$varname = ‘tireqty’;<br />

You can then use $$varname in place of $tireqty. For example, you can set the value of<br />

$tireqty as follows:<br />

$$varname = 5;<br />

This is exactly equivalent to<br />

$tireqty = 5;<br />

This approach might seem somewhat obscure, but we’ll revisit its use later. Instead of<br />

having to list <strong>and</strong> use each form variable separately, you can use a loop <strong>and</strong> variable to<br />

process them all automatically.You can find an example illustrating this in the section on<br />

for loops later in this chapter.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!