Original: Type-PHP manual notes
Type Introduction
PHP supports 8 types of raw data.
If you want to see the value and type of an expression, use a var_dump() function.
<?php $a = array(1, 2, array("a", "b", "c"));var_dump($a);$b = 3.1;$c = true;var_dump($b, $c);
The above code prints the information about the var_dump() variable, and the output is as follows (PHP version 5.5.12).
array (size=3) 0 => int 1 1 => int 2 2 => array (size=3) 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1)float 3.1boolean true
If you just want an easy-to-read type of expression for debugging, use a gettype() function. To view a type, do not use gettype() the is_type function. is_typethe parameters can be filtered using the.
If you want to cast a variable to a type, you can use a cast or a settype() function on it. Note that the variable will behave differently depending on its current type.
Boolean Boolean type
In particular, when converting to Boolean, the following values are considered false:
- An empty string, and the string "0"
- An array that does not include any elements
The return value is true as long as it is an object.
The following procedure can deepen the understanding of Boolean type conversions.
<?php var_dump((bool) array()); // boolean falsevar_dump((bool) ""); // boolean falsevar_dump((bool) "0"); // boolean falsevar_dump((bool) "00"); // boolean truevar_dump((bool) "false"); // boolean truevar_dump((bool) (new stdClass())); // boolean truevar_dump((bool) ((object) array())); // boolean true
Integer integer type
To use octal expressions, the number must be preceded by 0 (0).
To use hexadecimal representation, the number must be preceded by 0x.
To use binary representations, the numbers must be preceded by a 0b.
The binary representation of the integer is available from PHP 5.4.0.
The word length of an integer value can be PHP_INT_SIZE expressed as a constant, and the maximum value can be represented by a constant PHP_INT_MAX .
<?php var_dump(PHP_INT_SIZE); // int 4var_dump(PHP_INT_MAX); // int 2147483647var_dump(01090); // int 8 八进制 010 = 十进制 8
In the last statement of the above program, a strange thing happens when handling eight binary. That's because if you pass an illegal number (that is, 8 or 9) to the octal number, the remaining digits are ignored.
If a given number exceeds the range of integers, it will be interpreted as float. Similarly, float is returned if the result of the operation is outside the integer range.
Operators that do not have an integer division in PHP. 1/2 produces a float of 0.5. The value can be cast to integer by discarding the fractional part, or the round() function can be used for better rounding.
The manual says never to cast an unknown fraction to an integer, which can sometimes lead to unpredictable results.
<?php echo (int)((0.1 + 0.7) * 10);
The output of this program is 7, never trust floating point number!
float Float Type
Some mathematical operations produce a result that is represented by a constant NAN . This result represents a value that is undefined or not expressed in a floating-point operation. Any loose or strictly comparable result of this value to any other value is false.
String strings
A string of strings consists of a series of characters, each of which is equal to one byte. The implementation is a byte array followed by an integer indicating the buffer length. This means that PHP can only support a 256 character set and therefore does not support Unicode. How is the Chinese displayed? Write down the questions first.
The string has 4 syntax expressions:
- Single quotation marks
- Double quotes
- Heredoc
- Nowdoc
Single quotation marks
To express a single quotation mark itself, you need to escape it by adding a backslash (\) in front of it.
To express a backslash itself, use two backslashes (\).
Any other backslash will be treated as a backslash itself.
However, if there is only one backslash in the string wrapped in single quotation marks, the backslash will also be output, which is why?
Double quotes
Escape characters can be parsed, and the most important feature is that the variables are parsed.
Single and double quotes support string multi-line entry.
Heredoc structure
This structure has been used less in previous programming, and here is a detailed study.
The structure is roughly as follows:
Operator <<< , then provide an identifier and then wrap the line.
Next is the string itself.
Finally, use the previously defined identifier as the end flag.
The identifier that is referenced at the end must be in the first column of the row, which means that the identifier cannot be indented, except that there may be a semicolon (;), and it cannot contain any other characters.
The HEREDOCS structure cannot be used to initialize the properties of a class. Since PHP 5.3, this restriction is only valid for heredoc containing variables.
The HEREDOC structure is like a double-quoted string that does not use double quotes, and the escape rule is the same as double quotation marks.
Nowdoc structure
The NOWDOC structure is similar to Heredoc, except that <<< the identifiers followed by the operators are enclosed in single quotes.
Just as the heredoc structure resembles a double-quote string, the Nowdoc structure is similar to a single-quote string. Parse operation is not performed in Nowdoc. This structure is ideal for embedding PHP code or other large pieces of text without escaping special characters. The NOWDOC structure can be used in any static data environment, the most typical example being a property or constant used to initialize a class.
Variable resolution
There are two kinds of syntax rules for variable parsing, one is simple rule and one is complex rule. Simple rules are the most common, most convenient, here to learn more about complex grammar rules. The significant markup for complex rule syntax is an expression surrounded by curly braces.
Complex syntax is not named because of its complex syntax, but because it can use complex expressions. Because {cannot be escaped, only $ is recognized next to {.
Access and modification
The string can be accessed as an array, and an subscript written beyond the length of the string will lengthen the string and fill it with spaces. Bidding clubs are converted to integers under non-integer types. Only the first character of the assignment string is used when writing. Assigning a value with an empty string assigns a value that is a null character. The PHP string is internally an array of bytes. Therefore, it is not safe to use curly braces to access or modify strings to multibyte character sets.
Strings can be used '. ' (dot) operator, note that the ' + ' (plus) operator does not have this function.
A Boolean value of Boolean true is converted to string "1". The Boolean false is converted to "" (an empty string). The string is converted to a number, and the beginning of the string determines its value. If the string starts with a valid numeric value, the value is used. Otherwise its value is 0 (0).
The advantages of PHP are in the convenience of string processing, there are many useful functions for string manipulation, you can use a variety of functions, there are regular expressions.
PHP does not specifically indicate the encoding of the string, and the string is encoded in the same way as the script file. Therefore, the function that operates the text must assume how the string is encoded. Unfortunately, there are many variants of PHP's function, and the string-handling function for PHP requires more learning.
Array arrays
An array in PHP is actually an ordered map, which is a type that associates values with the keys.
You can use the array () language structure to create a new array. It accepts any number of "key (key) = = VALUES (value) pairs" separated by commas. You can use the short array definition syntax since 5.4 to replace array () with []. Key can be an integer or string,value can be any type.
Key will have the following casts and rules:
- A string containing a valid integer value is converted to an integral type.
- Floating-point numbers are also converted to integers, meaning that their fractional parts are removed.
- Boolean values are also converted to integral types.
- Null is converted to an empty string, that is, the key name null is actually stored as "".
- Arrays and objects cannot be used as key names.
- If more than one cell in the array definition uses the same key name, only the last one is used, and the previous is overwritten.
- If no key name is specified for the given value, the current largest integer index value is taken, and the new key name is the value plus one.
<?php $a = array('20' => 'a', '02' => 'b');var_dump($a);
The above rule shows that the output of this code is as follows:
array (size=2) 20 => string 'a' (length=1) '02' => string 'b' (length=1)
If the square brackets are given but no key name is specified, the current maximum integer index value is taken, and the new key name is the value plus 1 (but the minimum is 0). To delete a key-value pair, call the function on it, unset() which allows you to delete a key in the array, but be aware that the array will not rebuild the index.
<?php $a = array('a', 'b' => 'b');$a[] = 'c';var_dump($a);unset($a[1]);var_dump($a);
For the above program, the output is:
array (size=3) 0 => string 'a' (length=1) 'b' => string 'b' (length=1) 1 => string 'c' (length=1)array (size=2) 0 => string 'a' (length=1) 'b' => string 'b' (length=1)
You should always enclose the array index with a string representation. For example with $foo[‘bar‘] instead of $foo[bar] . There is an undefined constant (bar) in this code instead of a string (' bar '-note quotes), and PHP may define this constant later.
The foreach control structure is used exclusively for arrays. It provides a simple way to iterate through an array.
The following example program populates an array by reading the directory, which involves the use of several functions.
<?php $handle = opendir('.');while(false !== ($file = readdir($handle))) {$files[] = $file;}closedir($handle);var_dump($files);
For any Integer,float,string,boolean and resource type, if you convert a value to an array, you will get a list of only one element, with a subscript of 0, which is the value of this scalar.
Object objects
To create a new object objects, instantiate a class with the new statement.
If you convert an object to an object, it will not change. If any other type of value is converted to an object, an instance of the built-in class StdClass will be created. If the value is null, the new instance is empty. Converting an array into an object causes the key name to be the property name and has a corresponding value. For any other value, a member variable named scalar will contain the value.
<?php class foo {function do_foo() {echo 'Doint foo.';}}$bar = new foo;$bar->do_foo();var_dump($bar);$obj = (object) 'hello';var_dump($obj);
The above example program outputs the result:
Doint foo.object(foo)[1]object(stdClass)[2] public 'scalar' => string 'hello' (length=5)
Resource resource types
Resource resource is a special variable that holds a reference to an external resource. All external resources used by the resource are released by the garbage collection system, and there is little need to manually free up memory. However, persistent database connections are special, and they are not destroyed by the garbage collection system.
Null
A null type has only one value, which is a case-insensitive constant, NULL.
Callback Callback Type
The first exposure to this concept, a little strange.
You can specify the callback type callback from PHP 5.4 with the callable type.
A lot of functions are used in the manual sample program call_user_func , so let's get this function first. call_user_funcThe first parameter is used as the callback function (callback), and the remaining arguments are used as arguments to the callback function. Returns the return value of the callback function and returns False if the error occurs.
Callback functions can be simple functions, object methods, static class methods, and several methods of using callback functions are as follows:
- Invokes a user-defined simple function that passes its name as a string type.
<?php function my_callback_function() {echo 'hello, world.';}call_user_func('my_callback_function');
- Call the static member method of the class, the class and method are passed as an array, the subscript 0 contains the object, and the subscript 1 contains the method name.
<?php class MyClass {static function myCallbackMethod() {echo 'Hello, world.';}}call_user_func(array('MyClass', 'myCallbackMethod'));
- Invokes an object method that has been instantiated.
<?php class MyClass {static function myCallbackMethod() {echo 'Hello, world.';}}$obj = new MyClass;call_user_func(array($obj, 'myCallbackMethod'));
- Call the static class method.
<?php class MyClass {static function myCallbackMethod() {echo 'Hello, world.';}}call_user_func('MyClass::myCallbackMethod');
- Call the parent class static member method.
<?php class A {public static function who() {echo "A\n";}}class B extends A {public static function who() {echo "B\n";}}call_user_func(array('B', 'parent::who'));
In addition to ordinary user-defined functions, create_function() you can create an anonymous callback function.
Type conversions
PHP is a weakly typed language, and variable types are based on the context in which the variable is used.
(End of full text)
Type-PHP manual notes