Summary _php tutorial on knowledge accumulation in beginner PHP

Source: Internet
Author: User
Tags class operator php basics string back
PHP Basics
first, the initial knowledge of PHP
PHP is an embedded language used in combination with HTML.
1. PHP tags
Default tag Short Mark , you need to turn on the Short_open_tag option in php.ini short mark and other tags are not recommended

2, the keyword is not case-sensitive, the user-defined class name and function name are not case-sensitive, variable names are case-sensitive

3. Output
Boolean print (parameter) returns a bool value
void echo (parameter) No return value Echo's efficiency is a little higher.

Ii. Types of data
1. The usual way to compare two floating-point numbers is to move a number of decimal digits before converting to integer data for comparison.

2, double quotation mark delimiter string support variable name resolution, single quote delimiter string does not support variable name resolution.
$name = "Zhang San";
"$name"-Zhang San | | ' $name ' and $name | | "Mr. $name" and the Empty | | "{$name} Mr." = Mr. Zhang San | | "Mr. ${name}" and Mr. Zhang San

3. How the string is defined: single quotes, double quotes, and Heredoc (<<<>< p=""><>

4. The object type must be declared explicitly. Class is defined with the keyword class, using the keyword new to generate an instance of the class, accessing the properties and methods in the class with the symbol class
Class Car{public $COLOLR; function beep () {}} $mycar = new car; $mycar->color= ' red '; $mycar->beep ();

5, PHP is a weak language type, the type of the variable will be based on the given value of the self-determination, and often in the variable declaration at the same time the variable value assignment.

6. When a data type is cast, only the type name you want is written in parentheses before the variable.

Three, constants and variables
1, define constant define ("constant name", expression or value) constant name is recommended all uppercase, but not required
Use constants to directly use the defined constant name without adding "$" to the constant name
Predefined constants: _file_ the current PHP program file name _line_ the number of lines in the current PHP program (where to refer)

2, the variable does not need explicit declaration, when the variable is assigned the initial value of the variable is declared. If the variable is not set to the initial value, its initial value is null.

3, the assignment of variables: value assignment and reference assignment value. such as $a=& $b; That is, b originally pointed to a storage location, reference assignment, a also points to this storage location, at this time,
The destruction of a or B will not have any effect on the other, but if one of the values changes, the other will make the same change.

4, access to predefined variables using super global variables, a total of 9 super global variables

5. Local variables: variables defined within a function can only be used within a function
Global variables: Variables defined outside the function can only be used outside the function by default
To use global variables within a function, you need to declare the variable with global in the function, or use the Hyper global variable array &globals["variable name"
In PHP, only functions can provide local scopes.
The Hyper global variable $globals contains all the variables
The characteristics of static variables: only when the first call is initialized, the function is not destroyed after the end, and the next time it is used, the variable retains its original value.
Static variables can only be defined and used within a function.
mutable variable: The name of the variable is also used as a variable. $a =b; $b =c;$ $a = $b =c;
External variables: Up to 256 bytes of data can be passed using the Get method, with a maximum of 2MB post

Iv. Process Control (write-only differs from other languages such as Java)
1, interactive format (colon syntax) is not recommended, the classic is more intuitive

2. foreach (): This syntax is designed for arrays
The first format of foreach (Target_array as $value) statement
The second format is foreach (Target_array as $key = $value) statement

3. Break number: The number of layers to jump out of the structure
CONTIUE Number: The number of layers of the structure to jump out

4. The exit statement can end the execution of the current entire script and is typically used for error checking.
Exit Exit ("Cause of error");
Die () is the alias of exit $conn =mysql_connect ("localhost", "root", "") or Die ("Unable to connect to MySQL server");

Five, array
1. The only difference between an associative array and a numeric index array is the type of the index.

2, numeric index array
Initialize: Assign an array () function directly to an array element
If the array does not exist, the array element can be created at the same time that it is assigned a value
If the array elements are numbers in order, you can use the range () function when initializing arrays
Range () has 3 parameters, the first parameter specifies the initial value, the second parameter specifies the terminating value, and the third parameter is optional to specify the step size

3. Associative arrays
Initialize: Assign an array () function directly to an array element

4. Array-related operators
+ Union $a + $b will add $ to $ A, but any element with conflicting index values will not be added
= = equals $a = = $b if $ A and $b contain the same element, return True (the index value and element must be the same) in addition to the order, the others must be exactly the same
! = <> Not equal to
= = = Identical if $ A and $b contain the same elements in the same order, return True (index values and elements must be the same) must be exactly the same
!== not identical

5. Sorting of arrays
A Boolean sort () is arranged in numbers and alphabetical order, which assigns a new index value and the original index value is deleted
void Asort () keeps the original index relationship by sorting the array in ascending order
Integer ksort () arranged in ascending order by index value
Usort (array, method name) sorted by user-defined method
Array_multisort () sort multiple arrays at a time
Natsort () Sort by natural order, preserving the original index relationship after sorting
Natcasesort () Natural sort, case insensitive

6. Reverse ordering of arrays
Rsort () array elements sorted in descending order
Arsort ()
Krsort ()

7. Reordering the array
Boolean shuffle () random array of arrays
Array Array_reverse () resets the elements in the array
Array Array_flip () redeems the index in the array with its element value

8. Array traversal
Current () Gets the value of the element referred to in the array
Next () Moves the pointer of the array back one bit, returning the element value of the element to which the pointer points after the move
Prev () Moves the pointer of the array forward one bit, returning the element value of the element to which the pointer points after the move
Reset () pointer set back to the starting position of the 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 backward one
Returns an array of 4 elements with an index of 0,key,1,value
Key () returns the index value pointed to by the current pointer of the array
Array_walk () processes each element of an array in the same way
Array_reduce () applies the custom function to each element of the array in turn
9. Other array manipulation functions
List () extracts multiple values at once from an array and assigns values to multiple variables at the same time
Count ()/sizeof () computes the number of elements in the array

Six, the string in PHP
1. Accessing characters in a string
Three ways to define strings: single quotes, double quotes, and Heredoc
You can treat a string as an array. $test = "Hello"; $test {0}= "h"; curly braces are recommended to avoid confusion with arrays

2. Formatting of strings
The formatting of strings typically includes removing extra spaces from strings, casing conversions, adding and removing backslashes, and HTML formatting four parts
Remove spaces and other symbols

String Trim (string to be processed, filter string)
If you do not specify a filter string, the default is to remove spaces, tab characters, line feeds, carriage returns, string terminators, and Vertical tabs
You can use the ".." Specifies a range that needs to be removed, for example, "a." F "means removing A, B, C, D, E and F
Filters only the string's beginning and end characters, even if a filter string is specified, the middle part of the string does not participate in filtering
String Lrtim (string to be processed, filter string)
Remove whitespace and other special characters to the left of a string
Other Trim ()

String RTrim (string to be processed, filter string), alias function chop ()
Remove whitespace and other special characters to the right of the string
Other Trim ()

Conversion to case of string
Strtolower (string to be processed) converts all characters in the specified string to lowercase
Strtoupper (string to be processed) converts all characters in the specified string to uppercase
Ucfirst (string to be processed) checks the specified string and converts it to uppercase if the first character of the specified string is a letter
Ucword (string to be processed) converts the first letter of each word in the specified string to uppercase

Adding and removing backslashes
You should use the Addslashes () function to add a backslash before saving any strings to the database.
Before displaying user data, you should call the Stripslashes () function to remove the backslash
Addslashes (string to be processed) add backslash
Stripslashes (string to be processed) remove backslash

HTML formatting
NL2BR (the string to be processed) converts a newline character in a string into a label in HTML "
"To implement line breaks in the browser
Htmlspecialchars (string to be processed, whether to convert double and single quotes, character set)
You can make some special characters as normal text output, and no more HTML parsing
Second parameter: The default is to convert only double quotes, Ent_compat only convert double quotes ent_quotes Convert

Ent_noquotes do not convert
Third parameter: Specifies the character set used for the conversion, default is Iso-8859-1
Hemlentities (string to be processed, whether to convert double and single quotes, character set)
function as above, but can escape more special characters
Heml_entity_decode (string to be processed, whether to convert double and single quotes, character set)
You can reverse-convert the display string, and the converted string can be parsed by an HTML tag
Strip_tags (Pending string, allow reserved HTML tags)
Remove all HTML and PHP tags

3. Connection and segmentation of strings
Explode (delimiter, string, number of segmented string fragments) splits a string by the specified delimiter
If the delimiter is a string, the function is split according to each character in the string, rather than dividing it by the entire split string
Implode (a connector, an array that needs to be concatenated into a string) to concatenate some strings into a string through the specified connector
Join (connectors, arrays that need to be concatenated into strings) function with implode ()
SUBSTR (string, start position, fetch length) extracts a subset of substrings from a string
A negative start position will be given a substring starting at the end of the original string with a length that is the absolute value of the negative number
Extract length is negative, SUBSTRING takes to the countdown "Length" character before
It's not hard to understand,-it means starting from the back.
Strtok (string, delimiter) extracts a string fragment from the specified string
If the delimiter is a string, the function splits based on the first character in the string, not the entire string.
When the function is called to continuously split the string, only the first partition needs to specify the parameter str, after the first split, the system automatically
The record string and the position of the first split pointer continue to be called, and the function continues 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, simply pass the string back as a parameter to the function.
Split (delimiter, string, number of strings returned) breaks a string into multiple substrings by a specified delimiter

4. Comparison of strings
You can use = = to compare strings directly
strcmp (String 1, String 2) is sorted in dictionary order and is larger in the back. If equal, returns 0 if STR1 is greater than str2, returns a positive number, otherwise negative
Case sensitive
STRCASECMP (String 1, String 2) ibid., Case insensitive
STRNATCMP (String 1, String 2) string comparison in natural order, equal to return 0, greater than return positive, less than return negative, case sensitive
STRNATCASECMP (String 1, String 2) is compared in natural order and is case-insensitive

5. Finding and replacing strings
strstr (The searched string, the keyword to find) finds a matching string or character in a string, if found, returns a substring starting from the key in the STR character to the end of the string, or false if more than one is returned from the first match to the knot. Substring of the tail
Strisstr () function Ibid, difference, the function is not case-sensitive
strchr (The searched string, the keyword to find) finds the substring or character in a string to match, and the function starts from the end of the string, and if one is found, returns the substring starting at the end of the string, if more than one, and returns the first match starting at the end. Returns False if there is no match
Strpos (The string to find, the substring or character to look for, starting with the first offset character of the original string)
If one is found, returns the position, starting with 0, if more than one, returns the first, if not, returns flase
Offset cannot be negative, or you cannot start a lookup
Strrpos (the string to be searched for, the keyword to find, starting with the first offset character of the original string)
Search from the end of the string, if more than one, returns the first match of the countdown
Strripos (The string to find, the keyword to look for, starting with the first offset character of the original string)
function with Strrpos (), the difference is not case sensitive
Stripos (The string to find, the keyword to look for, starting with the first offset character of the original string)
function with Strpos () difference is not case sensitive
Str_replace (replaced by string or array, replaced by string or array, source string or array, number of times replaced)
Searchreplacesubject
Replace search in subject with replace
If search is an array, replace is a string, and replace replaces all the 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 extra replace, the elements in the extra search array are replaced by an empty string
Substr_replace (the original string to be manipulated, the string to replace, the starting position of the original string to be replaced, the number of characters in the original string being replaced) used to find and replace a specific substring in a string in the specified position
Start position: If positive, calculate from the beginning, if negative, start at tail
Length: If positive, indicates that a continuous length character from Start is replaced,
If negative, indicates that the length character is replaced from start to bottom
The Str_ireplace () function is the same as Substr_replace (), but the function is case-insensitive

6. Other commonly used string functions
Strlen (String) to calculate the length of the specified string
MD5 (string, flag) encrypts a string MD5 algorithm
The second parameter, if true, returns a 16-bit binary number, or false to return a 32-bit hexadecimal string, which defaults to False

Vii. object-oriented programming technology in PHP
1, the characteristics of the object
Encapsulation: An object is the most basic unit of encapsulation, a data structure encapsulated with the object name, and a collection of operations that can be applied to that data.
Like a box, we don't need to know what's in the box, just know what it's used for.
Inheritance: PHP does not support multiple inheritance, which is essentially code reuse, which means that subclasses can automatically have all the attributes of a parent class without having to build from scratch.
Polymorphic: The ability to use the context of a class to redefine or change the behavior of a class. Polymorphism allows an object to decide which behavior or method to execute based on the resulting parameters, while providing a unified interface to the outside.

2, the structure of the class
Class name
{
Defining attributes, using the keyword var
var $var 1;
var $var 2;
...
Defining methods, using the keyword function
function Method1 (...) {...}
function Method2 (...) {...}
...
It is not possible to define a class separately into multiple PHP tag pairs, and not to be separated into multiple files.

3. Instantiation of Class
Use the keyword new to create an instance of a class
$ instance Name =new class name;

4. Use the properties of the class
To use a property or method defined in a class, you can simply use the operator, "." You need to use the $this pointer if you need access to a property or method within a class that you define in the class definition.
In general, there is a risk of directly accessing the properties of a class from outside the class, and for this reason PHP provides some protection for accessing class properties. __set (), __get (), when the view references a
A property that does not exist in a class, these methods are called to handle it accordingly.

5. class's access control control class properties and methods
If you specify an access control type for a property of a class, the keyword VAR is omitted
Public can be accessed both inside and outside of the class. This option is the default option.
Use the "::" operator to access a function or variable in a class without creating an instance of any class
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 subclasses

6. Constructor function
Constructors are called automatically 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
Destructors are called before the class object is destroyed, and are typically used to set some of the actions that need to be done before the object is destroyed. The simplest way to destroy an object is to directly assign it a value of NULL
destructor Syntax: function __destruct () {}
At the end of the execution of the script, PHP automatically destroys all objects in memory. Therefore, you do not need to explicitly define destructors for generic class objects.
However, if the class object creates data that is not easily destroyed when it is instantiated, if the data is stored in the database rather than in memory, you should define a destructor in the class
object to be destroyed when the data is destroyed.

8. Static properties and methods
Static properties and methods require the use of the keyword "self::" to refer to, the other introduction of the previous article has

9. Class operator instanceof
You can tell if an object is an instance of a class

10. Inheriting existing classes
Inherit using keyword Extend

11. Overloading of Classes
Overloading refers to redefining the same properties and methods as the parent class in a subclass. Class is overloaded so that a property can be assigned a value that is not the same as its parent class in a subclass.
You can also assign a method to a function that is not the same as its parent class.

12. Accessing properties and methods in the parent class
A subclass can get properties and methods in the parent class through inheritance and overloading, and can override inherited properties and methods. But sometimes, in subclasses, you will need to directly
Invokes a method in the parent class. You can use the keyword "Parent::" in PHP to implement access to properties and methods in the parent class.

13. Use the final keyword to prohibit inheritance and overloading
When you use the keyword "final" in front of a function definition, it means that the function cannot be overloaded by any child classes.
If you do not want a class to inherit, simply add the "final" keyword to the class when you define it
If a property 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 class, but cannot be accessed directly outside the class
If a property or method in a class is specified as "public", the property or method can be inherited not only by the quilt class, but can be accessed from anywhere

14. Abstract classes and abstract methods
Abstract classes are classes that cannot be instantiated and can only be used as parent classes of other classes. So the subclass that inherits the abstract class must implement all the abstract methods.
Use the keyword "abstract" in PHP to define an abstract class and method.

15. Interface
An interface is a special kind of abstract class that typically contains only abstract methods and does not define attributes. The definition of a property and the implementation of an abstract method are given to the class implementing the interface.
Defines the interface using the keyword "interface" to implement the interface with the keyword "implements"

16. Implement multiple interfaces
Classes in PHP do not allow multiple inheritance, but allow multiple interfaces to be implemented

17. Assignment of objects
Target object = Clone original object; Copy the two objects exactly the same, but not interfering with each other
You can also use the __clone () method to adjust the behavior of an object assignment in PHP. By default, the function creates an object that has the same properties and methods as the original object, if you want to
To change something in the original object after the assignment, simply override the corresponding property and method in the original object in the method. The method can use the $this pointer

18. Automatic Loading class
PHP specifically provides the __autoload () function to automatically load the required classes.
The function is called automatically when it needs to be loaded, and the class name is passed to the __autoload () function as a parameter

19. Handling non-existent method calls
When a non-existent method in the calling class will produce a fatal error, PHP provides the __call () method to handle this type of error.

20, serialization of objects
To facilitate the transfer and storage of variables, it is common to convert them into a byte stream of strings before they are transmitted and stored, and when these variables are needed, revert them to
The original variable, the process becomes serialized and deserialized.
To facilitate the transfer and storage of class objects, the alignment can also be serialized and deserialized. PHP uses the function serialize () to serialize an object whose arguments are the object name,
The return value is the string that is obtained after serialization. Deserialization uses the Unserialize () function, whose argument is a string that returns the original object.
When the object is serialized, it automatically calls a method called __sleep () to do something before bedtime, which does not receive any arguments, but returns an array of
Specifies the attributes that need to be serialized, and attributes that are not included will be ignored at serialization time. If you do not specify the __sleep () method, PHP will serialize all of the properties.
When the object is deserialized, it automatically calls a method called __wakeup (), doing something that the object wakes up to do.

Viii. PHP Access MySQL Database
1. Basic steps of database operation
Link Database server mysql_connect (MySQL server host name, username, password);
Select a database mysql_select_db (database name, resource ID);
Operation of the database mysql_query (database statement, resource identification);
Processing of data records mysql_fetch_row (resource identification);

2. Connect and close the database
$connect = mysql_connect ("localhost", "root", "123456");
After you end the operation on the database, mysql_connect () automatically disconnects, or you can explicitly use Mysql_close () to disconnect.
Mysql_pconnect () establishes a persistent connection that, once the connection is established, is placed in the connection pool, even if the database operation ends
The connection is not automatically closed, but is reserved for later use. Even using the Mysql_close () function cannot be closed by the function mysql_pconnect () established
The connection.
After you complete the database operation, you should close the connection. However, closing is not required because PHP has garbage collection and automatically
Processing. Of course, you can close the connection explicitly, close the connection requires a resource identification number, or, if not specified, close the recently opened connection by default.
Mysql_close (Resource identification number);

3. Select Database
Select Database mysql_select_db (database name, resource identification number);

4. Querying the Database
Functions that perform query operations are mysql_query () and Mysql_db_query (). Where the function mysql_query () executes a SQL statement directly,
The function mysql_db_query () can execute SQL statements on the specified database.
mysql_query (SQL statement, resource identification number):
If the SQL statement is a query statement such as SELECT, Show, Expllain, describe, then a resource identification number is returned when execution succeeds, and false on failure
If the SQL statement is a different statement (INSERT, UPDATE, Delete, and so on), returns true on success and false on failure.
Mysql_db_query (database name, SQL statement, resource identification number) function as above, this sentence corresponds to the combination of mysql|_slect_db () and mysql_query ().

5. Acquiring and displaying data
Mysql_fetch_row (Resource identification number) returns the current record row in the query result set as an array, and moves the current row pointer down one row after the call to the result set
Mysql_fetch_array (Resource identification number) returns the current record row in the query result set as an array, and moves the current row down one row in the result set after the call
Note:mysql_fetch_row () returns an array of results that can only be accessed using a numeric subscript, and mysql_fetch_array () returns an array of array subscripts,
You can also access it using the field name, but Mysql_fetch_row () can get the fastest execution speed
MYSQL_FETCH_ASSOC (Resource identification number) returns the current record row in the query result set as an associative array, and moves the current row pointer down one row after the call to the result set
Mysql_fetch_object (Resource identification number) returns the current record row in the query result set as an object and moves the current row pointer down one row in the result set after the whine is used
The Mysql_result (Resource identification number, line number, field) field can use a numeric index, or you can use a field name. Digital index subscript starting from 0
The function returns the value of the specified field for the specified record row
Mysql_num_rows (Resource identification number) returns the number of record rows that match the query criteria
Mysql_field_seek (Resource identification number, positioned line number) to the row to query
Mysql_fetch_length (Resource identification number) is returned as a numeric index array, and each array element value corresponds to the number of bytes in a field

6, the deletion and modification of data and related operations
Use mysql_query () to complete data deletion and modification operation
int Mysql_affected_rows (Resource identification number) returns the number of records affected by INSERT, UPDATE, and delete
Mysql_num_rows () Valid only for SELECT statements

http://www.bkjia.com/PHPjc/327510.html www.bkjia.com true http://www.bkjia.com/PHPjc/327510.html techarticle PHP Basic One, the first knowledge of PHP PHP is a mixed use of HTML embedded language. 1. PHP tag default tag? The short mark and the Short_open_tag option in the php.ini will be opened in the short mark and its ...

  • 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.