PHP Tutorials

Type Casting

Type casting is specifying the type that a certain variable should be evaluated as for a particular statement. This is useful, for example, if you want to use just the integer portion of a floating-point number. Since integers aren’t allowed to have a decimal point, the decimal point and everything after it would be dropped in such a conversion.

NOTE

The first three are probably the most common. However, casts to array or object types are also supported.

If a cast is made to an array, the result is an array whose first element is the value of the variable before it was cast. If a cast is made to an object, an object is created with a member variable called scalar that contains the value of the variable before it was cast.

Casts of this sort are uncommon and doing so is discouraged.

Necessity of Type Casting
It’s not usually necessary to typecast a variable. Most of PHP’s functions will do this for you; PHP is said to handle types automatically.

Thus, type casting comes in handy occasionally for things such as converting from integers to doubles. It isn’t something you’ll use a lot, but when you do use it, it’s a lot quicker and easier than any other method would be.

Syntax
To typecast a variable, specify the type you wish the variable to become in parentheses, followed by the variable, as follows:

(type) $variable

NOTE

Since PHP ignores whitespace, spaces can be included between the parentheses and the type, as desired. Also, at your discretion, the type may be placed right next to the variable, without a space in between the two. There are no real style guidelines or concerns here, so what you do is up to you; basically, try to use what you find is most readable.

Type casting can be done between any of the following types (types listed with the same bullet point are the same):

(int) or (integer)

(real), (double), or (float)

(string)

(array)

(object)

The following example performs a type cast:



The first echo statement in this program shows that the decimal value 5.5 was really assigned to $myFloat. The second statement shows what the value of $myFloat is after a type cast to an integer.

However, it is important to note that this type-casting operation did not change the value of $myFloat as it is stored in the variable; if you want to change the type of the variable itself, you can assign the type-cast variable to itself, as follows:



This program’s output is simply:

5

NOTE

Assigning 5.5 to $myFloat again would cause PHP to automatically set the type of $myFloat back to float. Types may change commonly, so don’t rely on a type being preserved for a variable after type casting.

Filed under: Chapter 2 @ 10:25 pm

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress