Home >Backend Development >PHP Tutorial >PHP study notes (3): Introduction to data type conversion and constants, study notes constants_PHP tutorial
1. Mutual conversion of PHP data types
1. Forced conversion
Copy code The code is as follows:
// bool, int, float, string, array, object, null
bool settype ( mixed $var , string $type )
1) Will change the type of the original variable
Copy code The code is as follows:
$a= "123a"; // string
settype($a, "int"); // Don't miss the double quotes
var_dump($a);
2) Define before assignment without changing the original variable type
Copy code The code is as follows:
$a = "123abc";
$b = (int)"123abc";
var_dump($a);
Tips: To avoid memory overflow, integer type is 4 bytes (2.147E9), floating point type is 8 bytes
2. Automatic conversion
Automatic conversion according to the running environment, such as 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.
Copy code The code is as follows:
$foo = “0″; // $foo is a string (ASCII 48)
$foo = 2; // $foo is now an integer (2)
$foo = $foo 1.3; // $foo is now a float (3.3)
$foo = 5 “10 Small Pigs”; // $foo is an integer (15)
3. Variable test function
Copy code The code is as follows:
is_bool(), is_numeric(), is_float(), is_int()...
is_scalar() //Check whether the variable is a scalar
2. Declaration and use of constants
Copy code The code is as follows:
//Cannot be changed after definition, can be accessed anywhere
//The default is case sensitive, capitalize is used
//Constant values can only use scalars (int, float, string, bool)
//Constants must be assigned values when they are declared
define("constant name", "value")
Check if constant exists
Copy code The code is as follows:
bool defined ( string $name )
var_dump(defined('a')); //Don’t miss the quotation marks