Recently read the PHP programming animal book, in this record 1-6 chapters of the content points.
1.PHP Introduction
* PHP can do server-side programming, command-line programming (write script), client graphical interface
* PHP processing image using GD extension
* PHP config file php.ini document: https://php.net/manual/zh/configuration.file.php
* PHP Keywords (keywords are not case sensitive):
1. __class__, __dir__, __file__, __function__, __line__, __method__, __trait__, __holt_compiler () __
2. And, array, as, Echo, Enddeclare, ENDfor, Endforeach, endif, Endswitch, Endwhile, eval, exit, interface, INSTEADOF, list, Or, print, callable, instanceof, trait, Var, xor
* PHP built-in functions
2.PHP Data type * Data type
1. PHP data type Total Eight kinds: four scalar type (integer, float, String, Boolean), two compound (array, object), two special types (resource, NULL)
2. The integral type range is usually: -2^31 ~ 2^31-1 (4 bytes)
3. Floating-point and C-voice double-precision floating-point range, usually: between 1.7E-308 ~ 1.7E+308 (8 bytes), accurate to 15 digits
4. If you need higher precision or wider range, you can use BC or GM extensions
5. Floating-point values are just approximate representations of numbers, for example, in many systems, 3.5 actually means no 3.49999 .... This means that when writing code, try to avoid the assumption that the floating-point number is accurate, such as directly using = = to compare two floating-point numbers, the general method is to compare the previous several:
if (intval($aintval($b) *10000) { ... }
6. Variables are parsed in double quotes, not resolved in single quotes
7. Escape symbols can be parsed in double quotes, and only in single quotes and ' Will parse
8. The following value in PHP evaluates to false:
False, 0, 0.0, empty string and string ' 0 ', empty array, empty object, null value.
A value that is not true is false, including the value of all resource types (so can be judged directly)
9. Arrays are divided into ordinary arrays and associative arrays, and there are many ways to iterate over arrays, most commonly, foreach
10. Resources: Database connections, file connections are resources, Is_resource () determine whether a variable is a resource
11. Callback (callable): Some functions are called by other functions, such as Call_user_func (). Callback functions can be created through function declarations and closures.
NULL, case-insensitive, indicates that the variable has no value, and can be determined by is_null () to be null.
* Variable
1. The variable starts with $ and $$ represents the variable:
$foo = "Bar"; $$foo = "AAA"; Echo $bar //
2. Reference to a variable: the reference is the alias of the variable, and the original variable points to the same variable address, destroying (unset) one of the values that does not affect the other. function can return values by & reference (can avoid copying large strings and arrays)
function &retref () { $var = "php"; return$var;} $v = &retref (); // the function declaration and call need to bring the reference symbol &
3. PHP variables have four scopes: global, local, static, and function parameters
Unlike other languages, PHP can only provide local scopes in functions (only variables declared in a function are local variables), and local variables cannot be created in loops, nested, conditional branches, or other block types. function parameters are locally valid.
Local variables with the same name as global variables can be used in functions, and global variables can be used as follows:
$aaa = "BBB"; function print_aaa () { global$aaa; // declaring variables as global variables with global Print ($aaa); Print ($GLOBALS[' aaa ']); // or access the $globals array }
* Garbage Collection
PHP uses reference counts and write-time replication to manage memory. In PHP, the symbol table maps the variable name to an in-memory variable address, and when a variable is assigned to another variable, PHP does not copy the value using more memory, but changes the symbol table to indicate that the other variable points to the same variable address, and adds 1 to the reference count of the variable. At this point, the value of one of the variables is modified, and PHP allocates a chunk of memory to hold the value, and the original variable address reference count minus 1. The reference count is the number of variables that point to a variable address, and when the reference count value is 0 o'clock, the variable memory address is freed.
* Expressions and operators
1. Clone/new (Create new object)
2. ~ (bitwise reverse), << (shift left), >> (Shift right)
3.!=/<> (not equal to), = = = (Type and value are equal),!== (type or value unequal), & (bitwise AND), ^ (bitwise XOR), | (Bitwise OR)
4. + =, *=,/=,%=, &=, |=, ~=, ^=, <<=, >>=,. =
5. and (&&), or (| |), XOR (XOR),! (non),PS: Priority and ratio or high
* Implicit conversion
The actual type is implicitly type-converted when the required data type does not match the actual data type
1. String and numeric arithmetic operations are converted to numbers. A string to a number must have a number at the beginning of the string if there is a. or e/e will be converted to floating-point numbers, or 0.
2. String connection operation, the number will be converted to a string.
3. Comparison operators are compared by numeric size or dictionary order depending on the type of operation. It is important to note that if two strings are numbers, they are compared as a number. *ps: Dictionary order refers to ASCLL sequence, numbers < capital letters < lowercase letters. *
4. When used by bitwise operators, the binary form of the operand is used, and the return value is the same as the operand type. The string binary is manipulated, and the result returns a string, such as ~ returns a string corresponding to each bit of the string,& the return string is the same length as the shorter string, and the string returned is the same as the longer string.
5. <<, >> operand is not an integer will first be converted to integers, left N is the equivalent of multiplying by 2^n, the right shift with 0 supplement, the right shift operation is similar, the leftmost 0 supplement.
* Display type conversion (forced type conversion)
1. (object) to object, (array) to array, (unset) to null.
2. Type conversions affect only the way other operators parse variables, and do not change the value of the variable itself. Not all conversions work properly, converting an array to an integer type becomes 1, and converting to a string type changes to "array".
3. When an object is converted to an array, an associative array of objects that exposes the property is created. The inverse of an array to an object (an illegal property name cannot be accessed)
* Other operators
[Email protected]//shielding operation
2. ' ... '//execute the shell command and return the output, such as: ' ' echo ' ls/tmp ';
3.instanceof//Object type Test
4.INSTEADOF//For specifying trait
5.break
Break can specify the number of layers to jump out, so you can exit the outer loop from the inner layer
while (true) { while (true) { break // jump 2-layer loop }}
Break jumps out of this layer loop, continue skips this cycle, jumps to the next cycle condition judgment
6. You can use Do...while to ensure that the loop executes at least once
7.require loading a file that does not exist generates a fatal error, the script stops executing, and the include generates a warning that the script does not stop executing. So include some HTML header footers with include, require contains some library files.
8.exit Exit program, script stop execution, Die is the alias of exit
3. function * Function parameter passing mode
1. Pass by value and pass by reference, most of the cases by value, for large strings, arrays, objects, passing by value is an expensive operation.
2. When a parameter is passed by reference, the actual value is passed instead of the copy of the value, and the value of the variable can be directly modified inside the function.
3. Array function parameters are passed by value by default, and objects are passed by reference by default.
* Function Parameters
1. A function can have multiple parameters with default values, but must be placed after the parameter without a default value.
2.PHP functions can use variable parameters, which are declared without any parameters.
function // variable parameter function}
3. You can use Func_get_args (), Func_num_args (), Func_get_arg () to get function parameter information (variable parameters can only get parameter values in this way).
4. When a parameter is called, the missing parameter is reported as a warning, the missing parameter is set to NULL to run in the function, and the extra parameter ignores no hint.
* Type hint
When defining a function, you can limit the parameter type to NULL, a subclass of a class or class, an array, or a callback, which must be passed by the specified type, or a fatal error that can be caught is reported.
* Return Reference
1. The function declaration must be displayed when the declaration returns a reference, and the call must also be added & before the function.
2. This technique is sometimes used to efficiently return large strings and arrays from functions, whereas a write-time copy of PHP usually means that it is often unnecessary to return a reference, which is slower than the return value.
* Variable function
$func _name // call a function named $func_name () value
* Anonymous functions (also known as closures)
// the Usort parameter can be a callable type (closure) Usort ($arrayfunction($a$b use ($sortOption) { ... });
4. String * definition
1. Double quotes and Heredoc defined strings can parse variables, in order to separate variables from strings, you can use curly braces {}.
2. Single quotes define the variables that can be effective with the escape character only and '.
3.PRINTF ()//String format output sprintf ()//String format return
4. Use Echo, print, Print_r, var_dump when debugging (Echo is the language structure, others are functions)
5. Access string Single character: $string {$i}//$i is a string offset
* Encode and escape
- Html:htmlentities (), Htmlspecialchars ()//html special characters to HTML entities. Strip_tags ()//delete HTML tags, get_meta_tags ()//extract META tags
- URL: There are two ways to encode a URL, the difference is in how to handle spaces. Rawurlencode () Rawurldecode ()//Space->%20,urlencode () UrlDecode ()//Space->+ PS: Use these functions to encode only the part that is behind the domain name, or the : and/will also be encoded.
- SQL: You need to escape a character in a query condition, the escape method is simple, which is to precede a single quotation mark, double quotation mark, null character and backslash with a backslash. Addslashes ()//Add backslash stripslashes ()//Remove backslash
* string comparison
1.==, = = =, >, <, >=, <=
2. Sort by dictionary order: strcmp, strcasecmp; Sort by natural order (alphabetical and numeric): STRNATCMP, strnatcasecmp.
Natural sort: pic1.jpg pic5.jpg pic10.jpg pic50.jpg
Dictionary sort (Sort by ascll): pic1.jpg pic10.jpg pic5.jpg pic50.jpg
* String interception and segmentation
SUBSTR//Fetch string Substr_replace//Replace string sscanf ($string, $template)//Explode strings by template
Parse_url ()//Parse URL
Regular Expressions: The use of regular expressions is a way to deal with string matching and segmentation, such as parsing a log of a format, but more complex, when used to study.
$string= "Fredtflinestone"; $a sscanf ($string, "%st%s (%d)"); Print_r ($a); // =>array (0=>fred,1=>flintstone,2=>35)
5. Arrays
* PHP internally stores all arrays as associative arrays
* COUNT (), sizeof (), range (2,5), range (5,2), Range (' A ', ' Z ')
* The array itself implements the functions of list and HashMap, in addition to the use of array to achieve set intersection and sets, queue, stack and other functions
6. Object * Use variable value as identifier (variable name, class name, function name, etc.)
$object New Person ; // equivalent to $class $object New $class ; $account New Account (); $object = "Account"; ${$object}->init (5000, 100);
* Object reference
Once an object is created, it is passed by reference and does not replicate the entire object (both time consuming and memory-intensive)
* Shallow Copy object, can use clone
$p New $p 2 Clone $p;
When using clone, if there is a method named __clone () in the object's class definition, the class method can be called immediately after the object is copied (the hook function of clone). When an object has an external resource (such as a file handle, a database connection), you can use this feature to establish a new connection instead of copying an existing connection (you can use this feature to implement a deep copy).
* Class
1.PHP class names are case-sensitive
Class and method accessibility are public by default, and access identifiers such as public must be added when declaring attributes.
2. Accessing overridden methods in a parent class
Parent::method_name ();
3. Determine if an object belongs to a class
if ($objClass) {...}
* Feature Trait
Reuse code outside the class without having to create a parent class.
trait Logger { Public Log($logString) { $class _name=__class__; Echo Date(' y-m-d h:i:s '. ": [$class _name] [$log _string]" ); }}classUser { UseLogger; Public $name; function__construct ($name= ' ') { $this->name =$name; $this-Log(The Create User$name"); }}trait First {functionDofirst () {...}}trait Second {functionDosecnod () {...}}trait All { UseFirst,Second; functionDoall () {$this-Dofirst (); $this-Dosecond (); }}classCombined { UseAll ;}$obj=NewCombined ();$obj->doall ();
When using multiple trait method name collisions, you can specify which trait method to use, or give the method an alias.
class Person { use command,Marathon { commandas runCommand; Marathon::run Insteadof Command; }} $p New Person (); $p // Marathon Run $p // Command Run
* Introspection introspection (equivalent to reflection in Java)
Class_exists ()///Determine if the class exists get_declared_classes ()//Get the declared Class List get_class_methods ()//Get the name of the class method list Get_class_vars ()//Get the Class attribute array
* Object Inspection
Is_object ()///Determine if the object is Get_class ()//Get the Class name Method_exists ()//Determine if there is a method Get_object_vars ()//Get object property associative array Get_parent_class () Get Parent class Name
* Serialization of objects
Converts an object to a byte stream for easy storage and transport.
$bytes Serialize ($obj// serialization $objunserialize($bytes// deserialization
Serialization is available on the session store. During serialization and deserialization, PHP has two hook functions (hooks) __sleep () and __wakeup () for objects. Serialization is called before the __sleep, which can perform some cleanup work, such as closing the database connection, outputting unsaved persisted data, which returns an array of names of data members written to the byte stream, and if an empty array is returned, no data is written to the byte stream. The __wakeup () is called after deserialization, which can perform some initialization operations, such as rebuilding a database connection or opening a file.
This code block cannot be deleted ...
PHP Animal Book Summary (01-06)