Summary of knowledge accumulation during PHP beginners. PHP Basics 1. PHPPHP is an embedded language mixed with HTML. 1. what are the default PHP mark? Php? Short Mark ??, You need to enable the short_open_tag option in php. ini and its PHP Basics
I. first knowledge of PHP
PHP is an embedded language mixed with HTML.
1. PHP tag
Default tag Short Mark To enable the short_open_tag option in php. ini, short tag and other tags are not recommended.
2. keywords are case-insensitive. user-defined class names and function names are case-insensitive, and variable names are case-sensitive.
3. output
Boolean print (parameter) returns a boolean value.
Void echo (parameter) is more efficient than echo without return values.
II. Data types
1. the common method for comparing two floating point numbers is to move a number of decimal places first, convert them to integer data, and then compare them.
2. variable name parsing is supported for double quotation marks, while variable name parsing is not supported for single quotation marks.
$ Name = "James ";
"$ Name" => Mr. Zhang | '$ name' => $ name | "Mr. $ name" => null | "Mr. {$ name}" => Mr. Zhang San | "$ {name} Mr." => Mr. Zhang San
3. string definition: single quotes, double quotation marks, and heredoc (<
4. object types must be explicitly declared. Class is defined with the keyword class, the instance of this class is generated with the keyword new, and the attributes and methods in the symbol class category are used.
Class car {public $ cololr; function beep () {}}$ mycar = new car; $ mycar-> color = 'red'; $ mycar-> beep ();
5. PHP is a weak language type. the type of a variable is determined based on the assigned value, and the variable initial value is often assigned at the same time as the variable declaration.
6. during forced conversion of data types, you only need to write the required type name in brackets before the variable.
3. constants and variables
1. define the constant define ("constant name", expression or value). It is recommended that all the constant names be capitalized, but not required.
Use a constant to directly use the defined constant name. you do not need to add "$" before the constant name"
Predefined constant: _ FILE _ Current PHP program FILE name _ LINE _ number of lines of the current PHP program (where is it)
2. the variable does not need to be explicitly declared. when the initial value is assigned to the variable, the variable is declared. If no initial value is set for a variable, the initial value is NULL.
3. assign values to variables: assign values to input values and assign values to references. For example, $ a = & $ B; that is, B Originally points to a storage location. after a value is referenced, a also points to this storage location,
The destruction of a or B will not affect the other party, but if one of the values changes, the other will make the same change.
4. access the pre-defined variables using the hyper-global variables, a total of 9 super-global variables
5. local variables: variables defined in the function can only be used in the function.
Global variables: variables defined outside the function can only be used outside the function by default.
To use global variables in a function, you need to declare the variables in the function with global, or use the ultra-global variable array & GLOBALS ["variable name"]
In PHP, only functions provide partial scopes.
Super global variable $ GLOBALS contains all the variables
Static variables: initialization is performed only when the function is called for the first time. the function is not destroyed after the function is called, and the variable is retained for the next time.
Static variables can only be defined and used in functions.
Variable: the variable name is also used as a variable. $ A = B; $ B = c; $ a = $ B = c;
External variable: the maximum size of data that can be transferred using the GET method is 256 bytes, and the maximum size of data that can be transferred using the POST method is 2 MB.
4. process control (write only differs from other languages such as java)
1. the interactive format (colon syntax) is not recommended. it is classic and intuitive.
2. foreach (): this syntax is specially designed for arrays.
The first format is foreach (target_array as $ value) statement.
The second format is foreach (target_array as $ key => $ value) statement.
3. break number: number of layers of the structure to jump out
Contiue number: number of layers of the structure to jump out
4. the exit statement can end the execution of the entire script, which is usually used for error checks.
Exit; exit ("error cause ");
Die () is the alias of exit $ conn = mysql_connect ("localhost", "root", "") or die ("unable to connect to MySQL server ");
5. array
1. the only difference between an associated array and a digital index array is the index type.
2. numeric index array
Initialization: assign values to array elements directly to the array () function.
If the array does not exist, the array can be created when the array element is assigned a value.
If the array elements are sequentially arranged numbers, you can use the range () function during array initialization.
Range () has three parameters. The first parameter specifies the initial value, the second parameter specifies the end value, and the third parameter is optional, used to specify the step size.
3. associate an array
Initialization: assign values to array elements directly to the array () function.
4. array-related operators
+ After $ a + $ B is joined to $ a, elements with conflicting index values are not added.
= Equal to $ a = $ B if $ a and $ B contain the same element, true is returned (the index value and element must be the same) except for the order, the others must be the same
! = <> Not equal
=== Constant. if $ a and $ B have the same elements in the same order, true is returned (the index value and element must be the same ).
! = Non-constant
5. sort arrays
Boolean sort () is arranged in numbers and alphabetic order, and a new index value is assigned. the original index value is deleted.
Void asort () sorts arrays in ascending order and retains the original index relationship.
Integer ksort () is sorted by index value in ascending order
Usort (array, method name) is sorted by user-defined method
Array_multisort () sorts multiple arrays at a time.
Natsort () is sorted in the natural order, and the original index relationship is retained after sorting.
Natcasesort () is naturally sorted, case insensitive
6. reverse sorting of arrays
Rsort () sorts array elements in descending order
Arsort ()
Krsort ()
7. sort the array again
Boolean shuffle () random array arrangement
Array array_reverse () reverse the element in the array
Array array_flip () exchanges the index in the array with its element value
8. array traversal
Current () gets the element value specified by the current pointer in the array
Next () moves the pointer to an array one by one, and returns the element value pointed to by the pointer
Prev () moves the pointer of the array one byte forward and returns the element value of the element pointed to by the pointer after moving.
The reset () pointer is used to set the starting position of the returned array.
End () moves the pointer to the last element of the array.
Each () returns the "index/element value" pair pointed to by the current pointer in the array, and moves the array pointer one bit backward.
Returns an array containing four elements. the indexes of the array are 0, key, 1, and value.
Key () returns the index value pointed to by the current pointer of the array.
Array_walk () processes each element in the array in the same way.
Array_reduce () applies user-defined functions to each element of the array in sequence.
9. other array operation functions
List () extracts multiple values from an array at a time and assigns values to multiple variables at the same time.
Count ()/sizeof () calculate the number of elements in the array
6. Strings in PHP
1. access characters in strings
Three defining methods of strings: single quotes, double quotation marks, and Heredoc
Strings can be treated as arrays for processing. $ Test = "hello"; $ test {0} = "h"; braces are recommended to avoid confusion with arrays.
2. string formatting
String formatting usually includes four parts: Removing unnecessary spaces, case-sensitivity conversion, adding and deleting backslashes, and HTML formatting.
Remove spaces and other symbols
String trim (string to be processed, filter string)
If no filter string is specified, spaces, Tab characters, line breaks, carriage returns, string terminator, and Vertical tabs are removed by default.
You can use "..." to specify a range to be removed. for example, "a. f" indicates removing a, B, c, d, e, and f.
Only the first and last characters of a string are filtered. even if a filter string is specified, the middle part of the string is not filtered.
String lrtim (string to be processed, filter string)
Removes spaces and other special characters on the left of the string.
Others are the same as trim ()
String rtrim (string to be processed, filter string), alias function chop ()
Removes spaces and other special characters from the right of the string.
Others are the same as trim ()
String case-insensitive conversion
Strtolower (string to be processed) converts all characters in the specified string to lowercase letters
Strtoupper (string to be processed) converts all characters in the specified string to uppercase
Ucfirst (string to be processed) checks the specified string. if the first character of the specified string is a letter, convert it to uppercase.
Ucword converts the initial letter of each word in the specified string to uppercase.
Add and delete backslash
Before saving any string to the database, use the addslashes () function to add a backslash;
Call the stripslashes () function to remove the backslash before displaying user data.
Addslashes (string to be processed) add a backslash
Stripslashes (string to be processed) delete the backslash
HTML formatting
The nl2br (string to be processed) can convert the line breaks in the string into tags in HTML"
"To achieve line feed in the browser
Htmlspecialchars (string to be processed, whether to convert double quotation marks, single quotation marks, character set)
Some special characters can be used as common text output without HTML parsing.
Second parameter: by default, only double quotation marks are converted. ENT_COMPAT only converts both ENT_QUOTES and ENT_QUOTES.
ENT_NOQUOTES is not converted
Third parameter: specifies the character set used for conversion, default: ISO-8859-1
Hemlentities (string to be processed, whether to convert double quotation marks, single quotation marks, character set)
Functions are the same as above, but more special characters can be escaped.
Heml_entity_decode (string to be processed, whether to convert double quotation marks, single quotation marks, character set)
You can reverse convert the display string. the converted string can be parsed by HTML tags.
Strip_tags (string to be processed, HTML tags that can be retained)
Remove all HTML and PHP tags
3. string connection and Segmentation
Explode (separator, string, number of split string segments) splits a string according to the specified separator
If the delimiter is a string, the function splits the string based on each character instead of the entire string.
Implode (connector, which needs to be connected to an array of strings) concatenates some strings into a string through the specified connector
The join function is the same as the implode () function ()
Substr (string, start position, extract length) extract part of a substring from a string
The start position is negative. a substring starting from the end of the original string with the length of the negative value is obtained.
The extract length is negative, and the sub-string is taken before the last "length" character
This is not hard to understand.-it indicates starting from the end.
Strtok (string, separator) extracts a string segment from the specified string
If the delimiter is a string, the function splits the string based on the first character, instead of the entire string.
When you call this function to perform consecutive string segmentation, you must specify the str parameter only for the first split. after the first split, the system automatically
Record the position of the string and the pointer after the first split. if you continue to call this function, it will continue to be split from the current position of the string pointer.
. If you want to reset the pointer to the starting position of the string, you only need to pass the string back as a parameter to the function.
Split (separator, string, returns the number of strings) splits a string into multiple substrings according to the specified delimiter
4. string comparison
You can use = to directly compare strings.
Strcmp (String 1, string 2) is in the dictionary order and is placed at the bottom of the string. If the values are equal, 0 is returned. if str1 is greater than str2, a positive number is returned. Otherwise, a negative number is returned.
Case Sensitive
Strcasecmp (String 1, string 2) is the same as above, case insensitive
Strnatcmp (String 1, string 2) compares strings in the natural order, returns 0, greater than the return positive number, less than the return negative number, case sensitive
Strnatcasecmp (String 1, string 2) is compared in natural order, case insensitive
5. search and replace strings
Strstr (the searched string, the keyword to be searched) searches for the matched string or character in a string. if it is found, returns the substring starting from the key in the str string to the end of the string. If no substring is found, false is returned. if more than one substring exists, the substring from the first matched substring to the end is returned.
The strisstr () function is the same as the preceding one. it is case insensitive.
Strchr (the searched string, the keyword to be searched) searches for the substring or character to be matched in a string. this function starts from the end of the string. if one character string is found, returns the substring from the start of the key to the end of the string. if there is more than one substring, the first substring from the end is returned. If no substring is matched, false is returned.
Strpos (the string to be searched, the substring or character to be searched, starting from the offset character of the original string)
If one is found, the return position starts from 0. if more than one is found, the first is returned. if not, flase is returned.
The offset value cannot be negative. Otherwise, you cannot start searching.
Strrpos (the string to be searched for, the keyword to be searched, starting from the offset character of the original string)
Start from the end of the string. if more than one string exists, return the first to last match.
Strripos (the string to be searched, the keyword to be searched, starting from the offset character of the original string)
The function is the same as strrpos (). The difference is case insensitive.
Stripos (the string to be searched, the keyword to be searched, starting from the offset character of the original string)
Features are case insensitive to strpos ()
Str_replace (replaced string or array, replaced string or array, source string or array, number of times replaced)
Searchreplacesubject
Replace search with replace in subject
If search is an array and replace is a string, replace replaces all elements in the search array.
If both search and replace are arrays, the elements in replace will replace the corresponding elements in search.
If the number of elements in the search array is redundant, the elements in the redundant search array will be replaced by an empty string.
Substr_replace (the original string to be replaced, the start position of the original string to be replaced, and the number of characters in the original string to be replaced) used to find and replace a specific substring in a specified position.
Start position: if it is positive, it is calculated from the beginning. if it is negative, it is calculated from the end.
Length: if it is positive, the consecutive length characters starting from start are replaced,
If it is negative, the length from start to last is replaced
Str_ireplace () is the same as substr_replace (), but this function is case insensitive.
6. other common string functions
Strlen (string) is used to calculate the length of a specified string.
Md5 (string, flag) encrypts a string using the MD5 algorithm
If the second parameter is true, a 16-bit binary number is returned. if it is false, a 32-bit hexadecimal string is returned. the default value is false.
VII. object-oriented programming technology in PHP
1. object features
Encapsulation: an object is the most basic unit of encapsulation. it is the data structure encapsulated by the object name and a set of operations that can be applied to the data.
Just like a box, we don't need to know what is in the box, just know what uses it.
Inheritance: PHP does not support multi-inheritance. Inheritance is essentially code reuse. inheritance means that child classes can automatically have all the features of the parent class without building them from scratch.
Polymorphism: the context of a class can be used to redefine or change the behavior of a class. Polymorphism allows the object to decide which behavior or method to execute based on the obtained parameters, while providing a unified interface for external users.
2. class structure
Class name
{
// Define attributes and use the keyword var
Var $ var1;
Var $ var2;
...
// Define the method using the keyword function
Function method1 (...){...}
Function method2 (...){...}
...
} A class cannot be defined separately into multiple PHP tag pairs, but cannot be defined separately into multiple files.
3. class instantiation
Use the keyword new to create a class instance
$ Instance name = new class name;
4. use class attributes
To use the attributes or methods defined in the class, you only need to use the operator "->. If you need to define the attributes or methods defined in the category class, you need to use the $ this pointer.
In general, there is a certain risk to directly expose the attributes of the class from outside the class. For this reason, PHP provides some protection measures for the attributes of the category class. _ Set () ,__ get (), when the view references
When a property does not exist in the class, these methods are called for corresponding processing.
5. attributes and methods of class access control
If the access control type is specified for the class attribute, the keyword var must be omitted.
Public can be accessed both inside and outside the class. This is the default option.
You can use the ":" operator to create functions or variables in the category class without creating any class instances.
The format is as follows: class name: function class name: variable
Private can only be accessed within the class
Protected can only be used in this class and its subclass
6. constructor
Constructors are automatically called when a class is instantiated. PHP does not support multiple constructors.
The syntax format of the constructor is as follows: function _ construct (parameter 1, parameter 2 ,...){}
7. destructor
Destructor are called before the class object is destroyed. they are usually used to set the operations to be completed before the object is destroyed. The simplest way to destroy an object is to assign NULL values directly to it.
Destructor syntax: function _ destruct (){}
After the script is executed, PHP automatically destroys all objects in the memory. Therefore, you do not need to explicitly define the destructor for common class objects.
However, if a class object creates data that is not easily destroyed during instantiation, if the data is stored in the database rather than in the memory, an destructor should be defined.
The data can be destroyed normally when the object is destroyed.
8. static attributes and methods
Static attributes and methods must be referenced using the keyword "self :".
9. class operator instanceof
You can determine whether an object is an instance of a class.
10. inherit existing classes
Extend
11. class overloading
Overload refers to the re-defining of the same attributes and methods as the parent class in the subclass. Class overload allows you to assign a property to a subclass with a value different from its parent class,
You can also specify a function for a method that is different from its parent class.
12. access the attributes and methods in the parent class
A subclass can get the attributes and methods in the parent class through inheritance and overloading, and can override the inherited attributes and methods. However, in some cases
Call methods in the parent class. In PHP, you can use the keyword "parent:" to access attributes and methods in the parent class.
13. use final keywords to prohibit inheritance and overloading
When the keyword "final" is used before a function definition, this function cannot be overloaded by any subclass.
If you do not want to inherit a class, you only need to add the "final" keyword to it when defining the class.
If an attribute or method in a class is specified as "private", the property or method cannot be inherited.
If a property or method in a class is specified as "protected", the property or method can be inherited by the quilt class, but cannot be directly accessed outside the class.
If an attribute or method in a class is specified as "public", the property or method can be inherited by the quilt class and can be accessed anywhere.
14. abstract classes and abstract methods
An abstract class is a class that cannot be instantiated and can only be used as the parent class of other classes. Therefore, all abstract methods must be implemented to inherit the subclass of abstract classes.
Use the keyword "abstract" in PHP to define an abstract class and method.
15. interfaces
An interface is a special abstract class that generally only contains abstract methods and does not define attributes. Attribute Definitions and abstract methods are implemented by the class implementing the interface.
Define the interface using the keyword "interface" to implement the interface using the keyword "implements"
16. implement multiple interfaces
Classes in PHP do not allow multiple inheritance, but allow multiple interfaces.
17. Assignment of objects
Target Object = clone original object; the two objects are identical after replication, but do not interfere with each other
In PHP, you can also use the _ clone () method to adjust the behavior of object assignment. By default, this function creates an object with the same attributes and methods as the original object. if you want
After assigning values, you only need to override the corresponding attributes and methods of the original object in the method. This method can use the $ this pointer.
18. Automatic loading
PHP provides the _ autoload () function to automatically load the required classes.
When the function needs to be loaded, the function is automatically called, and the class name is passed to the _ autoload () function as a parameter.
19. handle non-existent method calls
When a non-existent method in the call class produces a fatal error, PHP provides the _ call () method to handle this type of error.
20. object serialization
To facilitate the transmission and storage of variables, variables are usually converted into byte streams of strings before they are transmitted and stored. when these variables are required, they are restored
The original variable, this process becomes serialization and deserialization.
To facilitate transmission and storage of class objects, you can also perform serialization and deserialization in alignment. Use the serialize () function in PHP to serialize an object. its parameter is the object name,
The returned value is the serialized string. Deserialization uses the unserialize () function. the parameter is a string and the original object is returned.
When the object is serialized, a _ sleep () method is automatically called to complete some bedtime tasks. this method does not receive any parameters, but returns an array in the array.
Specify the attribute to be serialized. uncontained attributes will be ignored during serialization. If the _ sleep () method is not specified, PHP will serialize all attributes.
During deserialization, an object will automatically call a method named _ wakeup () to do some actions that the object will do when it wakes up.
8. PHP accessing MySQL database
1. basic steps for database operations
Connect to the database server mysql_connect (MySQL server host name, user name, password );
Select a database mysql_select_db (database name, resource id );
Operate on the database mysql_query (database statement, resource id );
Process data records mysql_fetch_row (resource id );
2. connect to and close the database
$ Connect = mysql_connect ("localhost", "root", "123456 ");
After the database operation is completed, mysql_connect () will automatically disconnect, or you can explicitly use mysql_close () to disconnect.
Mysql_pconnect () is a persistent connection. Once a connection is established, the connection is stored in the connection pool, even if the database operation ends.
The connection will not be automatically closed, but will not be used later. Even if you use the mysql_close () function, you cannot close the function created by mysql_pconnect ().
.
After the database operation is completed, the connection should be closed. However, disabling is not necessary because PHP has the garbage collection function and will automatically perform unused connections.
Processing. Of course, you can explicitly close the connection. to close the connection, the resource ID is required. If no resource ID is specified, the last opened connection is closed by default.
Mysql_close (resource id );
3. select a database
Select database mysql_select_db (database name, resource id );
4. query databases
The query functions include mysql_query () and mysql_db_query (). The function mysql_query () directly executes an SQL statement,
The function mysql_db_query () can execute SQL statements on the specified database.
Mysql_query (SQL statement, resource ID ):
If the SQL statements are select, show, expllain, describe, and other query statements, a resource ID is returned when the execution is successful, and false if the execution fails.
If the SQL statement is other statements (insert, update, delete, etc.), true is returned when the statement is successful, and false is returned when the statement fails.
The function of mysql_db_query (database name, SQL statement, resource ID) is the same as that of mysql | _ slect_db () and mysql_query.
5. obtain and display data
Mysql_fetch_row (resource ID) returns the current record row in the query result set in the form of an array, and moves the current row pointer in the result set to one row after calling
Mysql_fetch_array (resource ID) returns the current record row in the query result set in the form of an array, and moves the current row in the result set to one row after calling
NOTE: the result array returned by mysql_fetch_row () can only be accessed by numerical subscript, and the returned result array by mysql_fetch_array () can be subscript,
You can also use the field name for access, but mysql_fetch_row () can get the fastest execution speed
Mysql_fetch_assoc (resource ID) returns the current record row in the query result set in the form of an associated array, and moves the current row pointer in the result set to one row after the call
Mysql_fetch_object (resource identification number) returns the current record row in the query result set in the form of an object, and moves the current row pointer in the result set to one row after the quota is used.
You can use a numeric index or field name for the mysql_result (resource ID number, row number, and field) field. Numeric index subscript starts from 0
This function returns the value of the specified field in the specified Record Row.
Mysql_num_rows (resource ID) returns the number of records that meet the query conditions
Mysql_field_seek (resource ID, locate row number) locate the row to be queried
Mysql_fetch_length (resource ID) is returned as a numerical index array, and each array element value corresponds to the number of bytes of a field
6. add, delete, and modify data and related operations
Use mysql_query () to add, delete, and modify data
Int mysql_affected_rows (resource ID number) returns the number of records affected by insert, update, and delete.
Mysql_num_rows () is only valid for select statements.
I. I first learned that PHP is an embedded language mixed with HTML. 1. what are the default PHP mark? Php? Short Mark? ?, You need to enable the short_open_tag option in php. ini and its...