Summary of knowledge accumulation during PHP beginners

Source: Internet
Author: User
Tags autoload class operator object serialization php basics string back

PHP Basics
I. First knowledge of PHP
PHP is an embedded language mixed with HTML.
1. PHP tag
Default tag <? Php?> Short mark <? ?>, You need to enable the short_open_tag option in php. ini. It is not recommended to enable the short tag and other tags.

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 linefeed in the string into the tag "<br>" in HTML to implement 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.