PHP does not need (or does not support) explicit type definitions in variable definitions. variable types are determined by the context in which the variable is used. That is to say, if a string value is assigned to the variable $ var, $ var becomes a string. If another integer value is assigned to $ var, it becomes an integer. PHP does not need (or does not support) explicit type definitions in variable definitions. variable types are determined by the context in which the variable is used. That is to say, if a string value is assigned to the variable $ var, $ var becomes a string. If another integer value is assigned to $ var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator "+ ". If any operand is a floating-point number, all the operands are treated as floating-point numbers, and the result is also a floating-point number. Otherwise, the operand is interpreted as an integer and the result is also an integer. Note that this does not change the type of these operands. it only changes how these operands are evaluated and the type of the expressions.
If you want to test any examples in this section, you can use the var_dump () function.
Note:
The behavior of automatically converting to an array is not defined currently.
In addition, because PHP supports accessing string subscript using the same syntax as array subscript, the following example is valid in all PHP versions:
$ A = 'car'; // $ a is a string
$ A [0] = 'B'; // $ a is still a string
Echo $ a; // bar
?>
Type forced conversion
The forced type conversion in PHP is very similar to that in C: add the target type enclosed in parentheses before the variable to be converted.
The following mandatory conversions are allowed:
(Int), (integer)-convert to integer
(Bool), (boolean)-convert to boolean type boolean
(Float), (double), (real)-convert to float
(String)-convert to string
(Array)-convert to array
(Object)-convert to object
(Unset)-convert to NULL (PHP 5)
(Binary) conversion and B prefix conversion support for PHP 5.2.1.
Note that empty spaces and tabs are allowed in parentheses, so the following two examples have the same functions:
$ Foo = (int) $ bar;
$ Foo = (int) $ bar;
?>
Convert string text and variables to binary strings:
$ Binary = (binary) $ string;
$ Binary = B "binary string ";
?>
Note:
You can place variables in double quotation marks instead of converting variables into strings:
Sometimes it is not obvious what exactly happens during forced conversions between types. For more information, see:
Convert to Boolean
Convert to integer
Convert to floating point
Convert to string
Convert to array
Convert to object
Convert to resource
Convert to NULL