This article mainly introduces PHP learning notes (3): Data type conversion and constant introduction. This article describes the mutual conversion of PHP Data types and the declaration and use of constants, for more information, see
I. conversion of PHP Data types
1. Forced conversion
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
The code is as follows:
$ A = "123a"; // string
Settype ($ a, "int"); // do not omit double quotation marks
Var_dump ($ );
2) defined before the value assignment, without changing the original variable type
The code is as follows:
$ A = "123abc ";
$ B = (int) "123abc ";
Var_dump ($ );
Tips: prevents memory overflow. the integer type is 4 bytes (2.147E9) and the floating point type is 8 bytes.
2. automatic conversion
Automatic conversion based on the running environment, such as the plus sign "+ ". 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.
The code is as follows:
$ Foo = "0"; // $ foo is a string (ASCII 48)
$ Foo + = 2; // $ foo is an integer (2)
$ Foo = $ foo + 1.3; // $ foo is now a floating point number (3.3)
$ Foo = 5 + "10 Small Pigs"; // $ foo is an integer (15)
3. variable test functions
The code is as follows:
Is_bool (), is_numeric (), is_float (), is_int ()...
Is_scalar () // checks whether the variable is a scalar.
II. Declaration and use of constants
The code is as follows:
// It cannot be changed after definition and can be accessed anywhere
// By default, it is case sensitive and is used to uppercase.
// Constant values can only be scalar (int, float, string, bool)
// Assign values when constants must be declared
Define ("constant name", "value ")
Check whether a constant exists
The code is as follows:
Bool defined (string $ name)
Var_dump (defined ('A'); // do not omit quotation marks