However, as you??™ll see in the next section, PHP will sometimes take the initiative
and cast a type to best fit the requirements of a given situation.
You can also cast a datatype to be a member of an array. The value being cast
simply becomes the first element of the array:
Table 3-2. Type Casting Operators
Cast Operators Conversion
(array) Array
(bool) or (boolean) Boolean
(int) or (integer) Integer
(int64) 64-bit integer (introduced in PHP 6)
(object) Object
(real) or (double) or (float) Float
(string) String
70 CHAPTER 3 ?– PHP B ASICS
$score = 1114;
$scoreboard = (array) $score;
echo $scoreboard[0]; // Outputs 1114
Note that this shouldn??™t be considered standard practice for adding items to an array
because this only seems to work for the very first member of a newly created array. If it
is cast against an existing array, that array will be wiped out, leaving only the newly cast
value in the first position. See Chapter 5 for more information about creating arrays.
One final example: any datatype can be cast as an object. The result is that the
variable becomes an attribute of the object, the attribute having the name scalar:
$model = "Toyota";
$obj = (object) $model;
The value can then be referenced as follows:
print $ obj->scalar; // returns "Toyota"
Adapting Datatypes with Type Juggling
Because of PHP??™s lax attitude toward type definitions, variables are sometimes automatically
cast to best fit the circumstances in which they are referenced.
Pages:
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155