|
Type JugglingPHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
If the last two examples above seem odd, see String conversion. If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype(). If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
Type CastingType casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
The casts allowed are:
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
It may not be obvious exactly what will happen when casting between certain types. For instance, the following should be noted. When casting from a scalar or a string variable to an array, the variable will become the first element of the array:
When casting from a scalar or a string variable to an object, the variable will become an attribute of the object; the attribute name will be 'scalar':
|
|||||||||||||||||||||||||
With any suggestions or questions please feel free to contact us |