In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you what are the knowledge points about PHP. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
PHP Foundation
First acquaintance of PHP
PHP is an embedded language mixed with HTML.
1. PHP tag
Default tag short tag, need to turn on the short_open_tag option in php.ini short tag and other tags are not recommended
2. Keywords are not case-sensitive, user-defined class names and function names are not case-sensitive, and variable names are case-sensitive.
3. Output
Boolean print (parameter) returns a Boolean value
Void echo (parameter) echo with no return value is more efficient.
2. Data type
1. The usual way to compare two floating-point numbers is to move several decimal places first, then convert them to integer data and then compare them.
2. Strings with double quotation marks as delimiters support variable name resolution, while strings with single quotation marks as delimiters do not support variable name resolution.
$name= "Zhang San"
"$name" = > Zhang San | |'$name'= > $name | | "Mr. $name" = > empty | | "{$name} Mr." = > Mr. Zhang San | | "${name} Mr. Zhang San"
3. How to define strings: single quotation marks, double quotation marks and heredoc (beep ()
5. PHP is a weak language type, and the type of variable is determined according to the given value, and the initial value of the variable is often assigned at the same time as the variable is declared.
6. When you cast a data type, you only need to write the required type name in parentheses before the variable.
Constants and variables
1. Define constant define ("constant name", expression or value) constant name is recommended in uppercase, but not required
Use a constant to directly use the defined constant name without adding "$" to the constant name.
Predefined constant: _ FILE_ current PHP program file name _ LINE_ the number of lines on which the current PHP program is located (where)
2. The variable does not need to be explicitly declared. It is declared when the initial value is assigned to the variable. If a variable is not set to an initial value, its initial value is NULL.
3. Variable assignment: transfer value assignment and reference assignment. For example, the original b points to a storage location, and after the reference assignment, an also points to this storage location, at this time
The destruction of either an 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. Use hyperglobal variables to access predefined variables, with a total of 9 hyperglobal variables
5. Local variables: variables defined within a function can only be used within a function
Global variables: variables defined outside a function can only be used outside a function by default
To use a global variable within a function, you need to declare the variable within the function with global, or use the super global variable array & GLOBALS [variable name]
In PHP, only functions can provide local scope.
The hyperglobal variable $GLOBALS contains all variables
The characteristics of a static variable: it is initialized only when it is called for the first time, it is not destroyed after the function ends, and the variable retains its original value the next time it is used.
Static variables can only be defined and used within functions.
Variable: the name of the variable is also used as a variable. $1 / 2 / 2 / 1 / 2 / 1 / 2 / 1 / 2 / 2 / 2 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 3 / 3 / 2 / 3 / 2 / 3 / 2 / 2 / 3 / 2 / 3 / 2 / 3 / 2 / 2 / 2 / 3 / 2 / 3 / 2 / 3 / 3 / 2.
External variables: the maximum data that can be transferred by GET is 256bytes, and the maximum by using POST is 2MB.
Fourth, process control (only different from other languages such as java)
1. Interactive format (colon syntax) is not recommended. The classic one is more intuitive.
2. Foreach (): this syntax is specially designed for arrays
The first format, foreach (target_array as $value) statement
The second format, foreach (target_array as $key= > $value) statement
3. Break number: the number of layers of the structure to be jumped out
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 usually used for error checking.
Exit; exit ("cause of error")
Die () is an alias for exit $conn=mysql_connect ("localhost", "root", "") or die ("unable to connect to the MySQL server")
V. Array
1. The only difference between an associative array and a numeric index array is the type of index.
2. Digital indexed array
Initialization: directly assign the array () function to array elements
If the array does not exist, the array can be created while assigning values to the array elements
If the array elements are sequential numbers, you can use the range () function when initializing the array
Range () has three parameters, the first parameter specifies the initial value, the second parameter specifies the end value, and the third parameter is optional to specify the step size
3. Associative array
Initialization: directly assign the array () function to array elements
4. Array-related operators
+ join $astatb to attach $to $a, but any elements with conflicting index values will not be added
= = equal to $aqqqb if $an and $b contain the same elements, return true (index values and elements must be the same) except in order, everything must be exactly the same
! = not equal to
= identical if $an 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
! = non-identical
5. Sort the array
When boolean sort () is arranged in numerical and alphabetical order, the new index value is assigned, and the original index value is deleted.
Void asort () sorts the array in ascending order and retains the original index relationship.
Integer ksort () is arranged in ascending order of index values.
Usort (array, method name) sorts by user-defined method
Array_multisort () sorts multiple arrays at a time
Natsort () is sorted in natural order, and the original index relationship is retained after sorting.
Natcasesort () natural sort, case-insensitive
6. Reverse sorting of arrays
Rsort () arranges array elements in descending order
Arsort ()
Krsort ()
7. Reorder the array
Boolean shuffle () randomly arranges the array
Array array_reverse () inverts the elements in the array
Array array_flip () converts the index in the array with its element value
8. Traversal of the array
Current () gets the element value referred to by the current pointer in the array
Next () moves the pointer of the array backward one bit, returning the element value of the element the pointer points to after the move.
Prev () moves the pointer of the array forward one bit, returning the element value of the element the pointer points to after the move.
The reset () pointer sets 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 bit
Returns an array of 4 elements with an index of 0magentic keyjournal 1Powervalue.
Key () returns the index value pointed to by the current pointer to the array
Array_walk () processes each element in the array in the same way
Array_reduce () applies the custom function to each element of the array in turn
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 () calculates the number of elements in the array
6. Strings in PHP
1. Access the characters in the string
There are three ways to define strings: single quotation marks, double quotation marks and Heredoc mode
Strings can be treated as arrays. $test= "hello"; $test {0} = "h"; braces are recommended to avoid confusion with arrays
2. Formatting the string
String formatting usually includes removing extra spaces in the string, case 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 feeds, carriage returns, string Terminators, and vertical tabs are removed by default
You can use ".." Specify a range to be removed, for example, "a.. f" means to remove a, b, c, d, e, and f
Only the beginning and end of the string are filtered, and even if the filtered string is specified, the middle part of the string will not participate in the filtering
String lrtim (string to be processed, filter string)
Remove spaces and other special characters on the left side of the string
Other same as trim ()
String rtrim (string to be processed, filtered string), alias function chop ()
Remove spaces and other special characters on the right side of the string
Other same as trim ()
Conversion of string case
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
Add and delete backslashes
Before saving any string to the database, you should use the addslashes () function to add a backslash
Before displaying user data, you should call the stripslashes () function to remove the backslash
Addslashes (string to be processed) add a backslash
Stripslashes (string to be processed) removes the backslash
HTML formatting
Nl2br (string to be processed) can convert newline characters in strings to tags in HTML. "
"to achieve line wrapping in the browser
Htmlspecialchars (string to be processed, whether to convert double and single quotes, character set)
You can make some special characters output as ordinary text without HTML parsing
Second parameter: only double quotation marks are converted by default, and only double quotation marks are converted by ENT_COMPAT. All ENT_QUOTES are converted.
ENT_NOQUOTES does not convert
The third parameter: specifies the character set used in the conversion, which defaults to ISO-8859-1
Hemlentities (string to be processed, whether to convert double and single quotes, character set)
The function is the same as above, but more special characters can be escaped
Heml_entity_decode (string to be processed, whether to convert double and single quotes, character set)
The display string can be converted in reverse, and the converted string can be parsed by HTML tag
Strip_tags (string to be processed, HTML tag allowed to be retained)
Remove all HTML and PHP tags
3. Concatenation and segmentation of strings
Explode (delimiter, string, number of string fragments split) splits a string by a specified delimiter
If the delimiter is a string, the function splits according to each character in the string, not the entire split string
Implode (an array of connectors that need to be concatenated into strings) concatenates some strings into a string through a specified connector.
Join (connectors, arrays that need to be concatenated into strings) function is the same as implode ()
Substr (string, start position, extract length) extract a molecular string from a string
If the starting position is negative, you will get a substring whose length is the absolute value of the negative number starting at the end of the original string.
The extraction length is negative, and the substring is taken before the penultimate "length" character.
It's not hard to understand.-it means starting from the back.
Strtok (string, delimiter) fetches a string fragment from the specified string
If the delimiter is a string, the function splits according to the first character in the string, not the entire string
When calling this function to continuously segment a string, only the parameter str needs to be specified for the first split, and after the first split, the system will automatically
Record the string and the first split pointer position, continue to call the function, it will continue to split from the current position of the string pointer
. If you want to reset the pointer to the beginning of the string, simply pass the string back to the function as an argument.
Split (delimiter, string, number of returned strings) decomposes a string into multiple substrings according to the specified delimiter
4. Comparison of strings
You can use = to compare strings directly
Strcmp (string 1, string 2) is the largest in dictionary order. Returns 0 if equal, positive if str1 is greater than str2, otherwise negative
Case sensitive
Strcasecmp (string 1, string 2) same as above, case-insensitive
Strnatcmp (string 1, string 2) compares strings in natural order, which is equal to returning 0, greater than returning positive numbers, less than returning negative numbers, and case-sensitive.
Strnatcasecmp (string 1, string 2) are compared in natural order, case-insensitive
5. Find and replace strings
Strstr (the string to be found, the keyword to be found) looks for a matching string or character in a string, and if found, returns the substring starting from the key in the str character to the end of the string, if not found, false, or, if there is more than one, the substring from the first match to the end
Strisstr () function is the same as above, different, this function is not case-sensitive
Strchr (the string to be found, the keyword to be found) looks for the substring or character to match in a string. This function starts at the end of the string. If one is found, it returns the substring from the key to the end of the string. If there is more than one, the first match from the end is returned. If there is no match, false is returned.
Strpos (the string to find, the substring or character to find, starting with the offset character of the original string)
If one is found, the position is returned, starting at 0, if there is more than one, the first one is returned, if not, flase is returned.
Offset cannot be negative, otherwise you cannot start searching
Strrpos (the string to be found and the keyword to be found, starting with the offset character of the original string)
Start at the end of the string, and if there is more than one, return the penultimate match
Strripos (the string to find, the keyword to find, starting with the offset character of the original string)
The function is the same as strrpos (), and is case-insensitive
Stripos (the string to find, the keyword to find, starting with the offset character of the original string)
The function is case-insensitive from strpos ().
Str_replace (replaced string or array, replaced string or array, source string or array, number of times replaced)
Searchreplacesubject
Replace search in subject with replace
If search is an array and replace is a string, all elements in the search array will be replaced in replace
If both search and replace are arrays, the element in replace replaces the corresponding element in search
If the number of elements in the search array is more than replace, the elements in the redundant search array will be replaced by an empty string
Substr_replace (the original string to be manipulated, the string to be replaced, the starting position of the original string to be replaced, the number of characters in the original string to be replaced) is used to find and replace specific substrings in the string at a specified location
Start position: if positive, calculate from the beginning, if negative, calculate from the end
Length: if positive, consecutive length characters starting from start are replaced
If negative, the character from the beginning of start to the penultimate length is replaced.
The str_ireplace () function is the same as substr_replace (), but the function is case-insensitive
6. Other commonly used string functions
Strlen (string) is used to calculate the length of a specified string
Md5 (string, flag) encrypts a string with MD5 algorithm
If the second parameter is true, it returns a 16-bit binary number; if false, it returns a 32-bit hexadecimal string. The default is false.
7. Object-oriented programming technology in PHP
1. Properties of objects
Encapsulation: an object is the most basic unit of encapsulation, a collection of data structures encapsulated by object names and operations that can be applied to that data.
Like a box, we don't need to know what's in the box, we just need to know what it does.
Inheritance: PHP does not support multiple inheritance. Inheritance is essentially code reuse. Inheritance means that subclasses can automatically have all the features of the parent class without having to build from scratch.
Polymorphism: you can use the context of a class to redefine or change the behavior of a class. Polymorphism enables objects to decide which behavior or method to execute according to the obtained parameters, while providing a unified interface to the outside world.
2. Structure of the class
Class class name
{
/ / define attributes, using the keyword var
Var $var1
Var $var2
...
/ / define the method, using the keyword function
Function method1 (...) {...}
Function method2 (...) {...}
...
} you cannot define a class separately into multiple PHP tag pairs, let alone into multiple files.
3. Instantiation of class
Use the keyword new to create an instance of the class
$instance name = new class name
4. Use the properties of the class
To use the properties or methods defined in the class, simply use the operator "- >". If you need to access properties or methods defined within the class itself when the class is defined, you need to use the $this pointer.
Generally speaking, it is risky to access the properties of a class directly from outside the class, so PHP provides some protection for accessing the properties of the class. _ _ set (), _ _ get (), when the view references a
When a property does not exist in the class, these methods are called to handle it accordingly.
5. Access control of the class attributes and methods of the control class
If the access control type is specified for the properties of the class, the keyword var needs to be omitted
Public is accessible both inside and outside the class. This option is the default.
Use the "::" operator to access functions or variables 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 inside the class
Protected can only be used in this class and its subclasses
6. Constructor
The constructor is 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
The destructor is called before the class object is destroyed and is usually used to set some operations that need to be done before the object is destroyed. The easiest way to destroy an object is to assign a NULL to it directly
Destructor syntax: function _ _ destruct () {}
At the end of the script execution, PHP automatically destroys all objects in memory. Therefore, there is no need to explicitly define destructors for general class objects.
But if the class object creates data that is not easy to destroy when instantiated, and if the data is stored in the database instead of in memory, you should define a destructor in the class
When the object is destroyed, the data can be destroyed normally.
8. Static properties and methods
Static properties and methods need to be referenced using the keyword "self::". Other introductions are already available.
9. Class operator instanceof
You can determine whether an object is an instance of a class.
10. Inherit existing classes
Inherit and use the keyword extend
11. Overloading of classes
Overloading refers to redefining the same properties and methods in the subclass as the parent class. Class overloading allows a property to be assigned a different value in a subclass than in its parent class
You can also assign a function to a method that is different from that in its parent class.
12. Access properties and methods in the parent class
A subclass can inherit and overload the properties and methods in the parent class, and can override the inherited properties and methods. But sometimes, in subclasses, you need to directly
Call a method in the parent class. The keyword "parent::" can be used in PHP to access properties and methods in the parent class.
13. Use the final keyword to disable inheritance and overloading
When the keyword "final" is used before a function definition, it means that the function cannot be overloaded by any subclass.
If you don't want a class to inherit, just 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 a subclass, 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 not only be inherited by the subclass, but can also be accessed anywhere
14. Abstract classes and abstract methods
Abstract classes are classes that cannot be instantiated and can only be used as parents of other classes. So subclasses that inherit abstract classes must implement all abstract methods.
Define an abstract class and method in PHP using the keyword "abstract".
15. Interface
Interface is a special abstract class, which usually contains only abstract methods and no properties. The definition of attributes and the implementation of abstract methods are left to the class that implements 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 to be implemented
17. Assignment of objects
Target object = clone original object; after replication, the two objects are exactly the same, but do not interfere with each other
You can also use the _ _ clone () method in PHP to adjust the behavior of object assignments. By default, this 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 assignment, you only need to override the corresponding properties and methods in the original object in the method. This method can use the $this pointer
18. Automatically load classes
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 an argument.
19. There is no method call to handle
A fatal error occurs when calling a method that does not exist in the class, and PHP provides a _ _ call () method to handle this type of error.
20. Serialization of objects
In order to facilitate the transmission and storage of variables, variables are usually converted into a byte stream of strings before they are transferred and stored, and when these variables are needed, they are restored to
The original variable, this process becomes serialization and deserialization.
To facilitate the transfer and storage of class objects, alignment can also be serialized and deserialized. The function serialize () is used in PHP to serialize an object, whose argument is the object name.
The return value is the serialized string. Deserialization uses the unserialize () function, whose argument is a string, and returns the original object.
When the object is serialized, it automatically calls a method named _ _ sleep () to do something before going to bed. This method does not take any parameters, but returns an array in the array
Specifies the properties that need to be serialized, and attributes that are not included will be ignored when serialized. If the _ _ sleep () method is not specified, PHP serializes all properties.
When an object is deserialized, it automatically calls a method called _ _ wakeup () to do something that the object wakes up to do.
VIII. PHP accesses MySQL database
1. Basic steps of database operation
Link database server mysql_connect (MySQL server hostname, user name, password)
Select a database mysql_select_db (database name, resource ID)
Operate on 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 finishing the operation on the database, mysql_connect () automatically disconnects, or you can explicitly disconnect using mysql_close ().
Mysql_pconnect () establishes a persistent connection, and once the connection is established, the connection 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 if you use the mysql_close () function, you cannot turn off the establishment of the function mysql_pconnect ().
The connection.
After completing the database operation, you should close the connection. However, shutdown is not necessary because PHP has a garbage collection feature and automatically performs unused connections
Deal with it. Of course, you can explicitly close the connection, which requires a resource identification number, and if not specified, the most recently opened connection is closed by default.
Mysql_close (Resource Identification number)
3. Select a database
Select database mysql_select_db (database name, resource identification number)
4. Query the database
The functions that perform query operations are mysql_query () and mysql_db_query (). Where the function mysql_query () directly executes a SQL statement
The function mysql_db_query () executes the SQL statement 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, etc., it will return a resource identification number on success and false on failure.
If the SQL statement is another statement (insert, update, delete, and so on), return true on success and false on failure.
The function of mysql_db_query (database name, SQL statement, resource identification number) is the same as above, which is equivalent to the combination of mysql | _ slect_db () and mysql_query ().
5. Obtain and display data
Mysql_fetch_row (Resource Identification number) returns the current row of records in the query result set as an array and moves the current row pointer down one line after the call
Mysql_fetch_array (Resource Identification number) returns the current record row in the query result set as an array and moves the current row in the result set down one row after the call
The result array returned by NOTE:mysql_fetch_row () can only be accessed using numeric subscript, while the result array returned by mysql_fetch_array () can be accessed by array subscript.
You can also use field names for access, but mysql_fetch_row () can get the fastest execution speed.
Mysql_fetch_assoc (Resource Identification number) returns the current row of records in the query result set as an associative array and moves the current row pointer down one row in the result set after the call
Mysql_fetch_object (Resource Identification number) returns the current row of records in the query result set as an object, and moves the current row pointer down one line after usage
The mysql_result (resource identification number, line number, field) field can use either a numeric index or a field name. Numeric index subscript starts at 0
This function returns the value of the specified field of the specified record row
Mysql_num_rows (resource identification number) returns the number of rows of records that meet the query criteria
Mysql_field_seek (resource identification number, located line number) navigates to the row to be queried
Mysql_fetch_length (Resource Identification number) is returned as a numerically indexed array, and each array element value corresponds to the number of bytes in a field.
6. Addition, deletion and modification of data and related operations
Use mysql_query () to complete the operation of adding, deleting and modifying data
Int mysql_affected_rows (resource identification number) returns the number of records affected by insert, update, and delete
Mysql_num_rows () is valid only for select statements
Thank you for reading! This is the end of this article on "what are the knowledge points of PHP?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.