PHP is a loosely typed language. There is no need to specifically define the variables used, which brings great flexibility and convenience to program writing. But when we write programs, we need to know what type of variables we use, because variables always have a type corresponding to them. Although you can almost freely convert between types, if you use or convert variable types arbitrarily, it may lead to some potential errors
Type coercion in PHP is very similar to that in C: add before the variable to be converted Target type enclosed in parentheses:
The code is as follows | Copy code | ||||
$bar = (boolean) $foo; // $bar is Boolean ?> |
Type conversion
PHP does not require (or support) explicit type definitions in variable definitions; the variable type is determined based on the context in which the variable is used. That is, if you assign a string value to the variable var, var becomes a string. If you assign an integer value to var, it becomes an integer.
An example of PHP's automatic type conversion is the plus sign "+". If any operand is a floating point number, all operands are treated as floating point numbers, and the result is also a floating point number. Otherwise the operands are interpreted as integers and the result is also an integer. Note that this does not change the types of the operands themselves; only how the operands are evaluated and the type of the expression itself is changed.
代码如下 | 复制代码 |
$foo = 10; // $foo 为整型 $bar = (boolean) $foo; // $bar 为布尔型 ?> |
Type casting in PHP is very much like in C: the variable to be converted is preceded by the target type enclosed in parentheses:
The code is as follows | Copy code |
$foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is Boolean ?> |
(bool) or (boolean) - Convert to boolean
(float) or (double) or (real) - Convert to floating point type代码如下 | 复制代码 |
$foo = 10; // $foo 为整型 |
(array) - Convert to array
(object) - Convert to object
代码如下 | 复制代码 |
$str=www.bKjia.c0m; |
The code is as follows | Copy code |
$foo = 10; // $foo is an integer <🎜> $str = "$foo"; // $str is a string<🎜> ?> |
The code is as follows | Copy code |
$str=www.bKjia.c0m; $int = intval($str); This way $int=0;. |
When a string is evaluated as a number, the following rules are used to determine the type and value of the result:
If it contains any of the characters ".", "e" or "E", the string is evaluated as a float, otherwise it is treated as an integer
The value is determined by the first part of the string. If the string begins with legal numeric data, that number is used as its value, otherwise its value is 0 (zero). Legal numeric data begins with an optional sign, followed by one or more digits (optionally including a decimal fraction), followed by an optional exponent. The exponent is an "e" or "E" followed by one or more digits
Example:
The code is as follows
|
Copy code
|
||||
$foo = 1 + "10.5"; // $foo is a floating point type: 11.5 |
$foo = 1 + "bob3"; // $foo is an integer: 1