Use the resources of the curtain Course Network to reorganize the basic PHP knowledge for memo.

Source: Internet
Author: User
Tags object serialization
Original article: www. imooc. comlearn26 determines whether a function exists. When we create a UDF and understand the usage of a variable function, to ensure that the function called by the program exists, function_exists is often used to determine whether a function exists. The same method_exists can be used to check whether class methods exist. Class is

Http://www.imooc.com/learn/26 determines whether a function exists when we create a UDF and understand the usage of the variable function, in order to ensure that the function called by the program exists, function_exists is often used to determine whether a function exists. The same method_exists can be used to check whether class methods exist. Class is

Original article: http://www.imooc.com/learn/26

Determine whether a function exists

When we create a custom function and understand the usage of the variable function, to ensure that the function called by the program exists, function_exists is often used to determine whether the function exists. The same method_exists can be used to check whether class methods exist.


Whether the class can be defined using class_exists.

PHP has many such check methods, such as whether the file exists file_exists.

Class attributes and Methods

The variables defined in the class are called attributes, and the functions defined in the class are methods.

The keyword of access control indicates:

Public: public

Protected: protected

Private: private

Constructor and destructor

PHP5 can use _ construct () in the class to define a constructor. classes with constructor will call this function each time an object is created, therefore, it is often used for initialization when an object is created.

If _ construct is defined in the subclass, the _ construct of the parent class is not called. If you need to call the constructor of the parent class at the same time, you need to use parent ::__ construct () explicit call.


Similarly, PHP5 supports destructor defined using _ destruct (), which means that when all references to an object are deleted, or the function that will be executed when the object is explicitly destroyed.


After the PHP code is executed, the object is automatically recycled and destroyed. Therefore, you do not need to explicitly destroy the object.

Access Control

In the previous section, we have already touched on access control, which is implemented by the public, protected, and private keywords. It is defined as a public class member that can be accessed anywhere. A protected class member can be accessed by itself, its subclass, and its parent class. A private class member can only be accessed by the class it defines.

Class attributes must be defined as public, protected, or private. To be compatible with versions earlier than PHP5, if var is used, it is considered public.


Classes can be defined as public, private, or protected. If these keywords are not set, the method is public by default.

If the constructor is defined as a private method, the object cannot be directly instantiated. In this case, the static method is generally used to instantiate the object. In the design mode, this method is often used to control the creation of the object, for example, in singleton mode, only one globally unique object is allowed.

Static keywords

Static attributes and methods can be called without instantiating a class. They can be called directly using the Class Name: method name. Static attributes cannot be called using the-> operator.

Static methods can also be dynamically called through variables.

$ This pseudo variable is not allowed in static methods. You can use self, parent, and static to call static methods and attributes internally.

Object Inheritance

Inheritance is a common feature in Object-Oriented Programming. Automobile is a relatively large class, which can also be called a base class. In addition, cars are also divided into trucks, cars, Dongfeng, BMW, etc. Because these subclasses have many identical attributes and methods, you can inherit the automobile class to share these attributes and methods to achieve code reuse.

When a class is extended, the subclass inherits all the protected and public attributes and methods of the parent class. The subclass can also overwrite the corresponding methods of the parent class.

Heavy Load

PHP overload refers to the dynamic creation of attributes and methods, which are achieved through magic. You can use _ set ,__ get ,__ isset ,__ unset to assign values to, read, and determine whether to set or destroy a property that does not exist.

Method Overloading is implemented through _ call. When a nonexistent method is called, it is converted to a parameter call _ call method, _ callStatic is used to call a non-existent static method.

Advanced features of Objects

Object comparison: When all the attributes of the two instances of the same class are equal, you can use the comparison operator = to determine whether the two variables are referenced by the same object, you can use the equal-Sum Operator = to determine.

Object replication. In some special cases, you can use the keyword clone to copy an object. In this case, the _ clone method is called to set the attribute value through this magic method.

Object serialization: You can use the serialize method to serialize an object into a string to store or transmit data, and then use the unserialize method to deserialize the string into an object.

String Introduction


Returns the length of a string.

String Truncation

English character truncation:

Substr (STRING variable, start position, number of interceptions)

Chinese string truncation:

Mb_substr (STRING variable, starting position, number of interceptions, webpage encoding)

Regular Expression

Basic regular expression syntax

In the PCRE Library Function, regular expression matching uses separators and metacharacters. separators can be non-numeric, non-diagonal lines, and non-space characters. Frequently Used delimiters are forward slashes (/), hash symbols (#), and reverse symbols (~), For example:

/Foobar/
# ^ [^ 0-9] $ #
~ Php ~

If the mode contains delimiters, the delimiters must be escaped using a backslash.

/Http :\/\//

If the mode contains many delimiter characters, we recommend that you replace other characters as separators, or use preg_quote for escape.

You can use a pattern modifier after the separator. The pattern modifier includes: I, m, s, and x. For example, you can use an I modifier to ignore case-insensitive matching:

Metacharacter and escape

The characters with special meanings in regular expressions are called metacharacters. Common metacharacters include:

\ Is generally used for escape characters

^ Start position of the assertion target (or the first row in multi-row Mode)

$ End position of the assertion target (or end of a row in multi-row Mode)

. Match any character except the line break (default)

[Start character class definition

] End character class definition

| Start an optional Branch

(Start mark of the Sub-group

) End tag of the Sub-group

? As a quantizer, it indicates 0 or 1 match. It is behind the quantifiers to change the greedy nature of quantifiers. (Query quantifiers)

* Quantifiers, matching 0 or multiple times

+ Quantifiers, matching once or multiple times

{Start tag of custom quantifiers

} Custom quantifiers end mark

Metacharacters can be used in either of the following scenarios:

\ Escape characters

^ If it is used only as the first character (inside square brackets), it indicates that the character class is reversed.

-Mark character range

^ Indicates the start position of the assertion target, but inside the square brackets, it indicates the inverse of the character class. The minus sign in the square brackets can mark the character range, for example, 0-9 indicates all numbers between 0 and 9.

Greedy mode and lazy Mode

In a regular expression, each metacharacter matches one character. When + is used, it will become greedy. It will match as many characters as possible, but will use question marks? It matches as few characters as possible, which is both a lazy mode.

Greedy mode: priority is given to matching and mismatch.

Lazy mode: when matching or not matching, the Priority does not match

When we know exactly the length of the matched characters, we can use {} to specify the number of matching characters.

Use regular expressions for matching

Regular expressions are used to implement more flexible processing methods than string processing functions. Therefore, they are the same as string processing functions, it is mainly used to determine whether a sub-string exists, replace the string, split the string, and obtain the mode sub-string.

PHP uses the PCRE Library Function for Regular Expression Processing. By setting the mode, it calls the relevant processing function to obtain matching results.

Preg_match is used to execute a match. It can be used to determine whether the pattern matches successfully or obtain a matching result. The returned value is the number of successful matches (0 or 1, the search will be stopped after matching once.

The above Code simply executes a match, and simply determines whether def can be matched successfully. However, the strong aspect of the regular expression is pattern matching. Therefore, when there are more, usage mode:

Search all matching results

Preg_match can only match the results once, but many times we need to match all the results. preg_match_all can obtain a list of matching result arrays cyclically.

You can use preg_match_all to match the data in a table:

Search and replace regular expressions

Regular Expression search and replacement are important in some aspects, such as adjusting the format of the target string and changing the order of matching strings in the target string.

For example, we can simply adjust the date format of the string:

$ {1} is equivalent to $1, which indicates the first matching string and $2 indicates the second matching string.

Through the complex mode, we can replace the content of the target string more accurately.

Use regular expression replacement to Remove extra spaces and characters:

Common cases of Regular Expression matching

Cookie Introduction

Cookie is the data stored in the client browser. We track and store user data through cookies. Generally, the Cookie is returned from the server to the client through HTTP headers. Most web programs support Cookie operations. Because cookies exist in the HTTP header, they must be set before other information is output, similar to the use restrictions of header functions.

PHP uses the setcookie function to set the Cookie. Any Cookie sent back from the browser will automatically store it in the global variable of $ _ COOKIE, therefore, we can read a COOKIE value in the form of $ _ Cookie ['key.

Cookies in PHP are widely used and are often used to store user login information, shopping cart, and so on. In Session, cookies are often used to store Session IDs to identify users, the Cookie has a validity period. After the validity period ends, the Cookie is automatically deleted from the client. At the same time, for security control, Cookie can also set the domain and Path

The most common method for setting a Cookie in PHP is to use the setcookie function. setcookie has seven optional parameters. The first five parameters are commonly used:

Name (Cookie name) can be accessed through $ _ COOKIE ['name ']

Value (Cookie value)

Expire (expiration time) Unix timestamp format. The default value is 0, indicating that the browser is disabled or becomes invalid.

Path (valid path) if the path is set to '/', the entire website is valid.

Domain (valid domain) is valid for the entire domain name by default. If 'www .imooc.com 'is set, it is valid only in the www subdomain.

There is also a function setrawcookie in PHP to set cookies. setrawcookie is basically the same as setcookie. The only difference is that the value does not automatically perform urlencode. Therefore, you need to manually perform urlencode when necessary.

Setrawcookie ('cookie _ name', rawurlencode ($ value), time () + 60*60*24*365 );

Because the Cookie is set through the HTTP header, you can also use the header method directly.

Header ("Set-Cookie: cookie_name = value ");

Cookie deletion and expiration time

Through the previous chapter, we learned about the cookie setting function, but we found that php does not delete the Cookie function. In PHP, The setcookie function is also used to delete the cookie.

Setcookie ('test', '', time ()-1 );

You can see that the cookie will expire automatically before the current time, so as to delete the cookie. This design is because the cookie is transmitted through the HTTP header. The client sets the Cookie Based on the Set-cookie segment returned by the server, if you need to use a new Del-cookie to delete a Cookie, the HTTP header becomes more complex, in fact, you can Set, update, and delete cookies simply and clearly through Set-Cookie.

After understanding the principle, we can also directly Delete the cookie through the header.

Header ("Set-Cookie: test = 1393832059; expires = ". gmdate ('d, d m y h: I: s \ G \ M \ t', time ()-1 ));

Gmdate is used to generate Greenwich mean time to eliminate the effect of time difference.

Valid cookie Path

The path in the cookie is used to control the path under which the set cookie is valid. The default value is '/', which is available in all paths. After other paths are set, it is only valid under the specified path and sub-path, for example:

Setcookie ('test', time (), 0, '/path ');

The above settings will make test valid in/path and sub-path/abc, but the cookie value of test cannot be read in the root directory.

Generally, all paths are used. The path is set only when there are very few special requirements. In this case, the cookie value is passed only in the specified path, it can save data transmission, enhance security and improve performance.

When we set a valid path, the current cookie will not be visible if it is not in the current path.

Setcookie ('test', '1', 0, '/path ');
Var_dump ($ _ COOKIE ['test']);

Session and cookie

Cookie stores data on the client and establishes connections between users and servers. It can solve many problems, but cookies still have some limitations:

The cookie is not too secure and is prone to theft, resulting in cookie spoofing.

The maximum value of a single cookie is 4 kb.

Network Transmission is required for each request, occupying the bandwidth

Session stores user session data on the server without size restrictions. You can use a session_id to identify the user. By default, session IDs are saved through cookies in PHP, therefore, to some extent, seesion depends on cookies. However, this is not absolute. sessionid can also be implemented through parameters. As long as the session id can be passed to the server for recognition, sessions can be used.

Use session

It is very easy to use session in PHP. First, execute the session_start method to enable the session, and then use the global variable $ _ SESSION to read and write the session.

The session automatically performs encode and decode on the value to be set. Therefore, the session can support any data type, including data and objects.

By default, sessions are stored on the server as files. Therefore, when a session is enabled on a page, the session file is exclusive, this will cause other concurrent accesses of the current user to wait for execution. You can use cache or database storage to solve this problem. We will discuss this in some advanced courses.

Delete and destroy a session

You can use the PHP unset function to delete a session value. After deletion, the value is removed from the global variable $ _ SESSION and cannot be accessed.

To delete all sessions, you can use the session_destroy function to destroy the current session. session_destroy deletes all data, but session_id still exists.

It is worth noting that session_destroy does not immediately destroy the value in the global variable $ _ SESSION. $ _ SESSION is empty only when you access it again next time, therefore, you can use the unset function to destroy $ _ SESSION immediately.

If you need to destroy session_id in the cookie at the same time, it is usually used when the user exits, you also need to explicitly call the setcookie method to delete the cookie value of session_id.

Use session to store user login information

Sessions can be used to store various types of data. Therefore, sessions are used to store user login information, shopping cart data, or temporary data.

After successful logon, users can usually store their information in sessions. Generally, important fields are stored separately, and all user information is stored independently.

Generally, login information can be stored in sessioin or cookie. The difference between them is that session can easily access multiple data types, while cookie only supports string types, at the same time, for some highly secure data, the cookie needs to be formatted and encrypted, while the session is stored on the server, which is highly secure.

Read File Content

Determine whether a file exists

Generally, when operating on a file, you must first determine whether the file exists. in PHP, the function is often used to determine whether the file exists. There are two is_file and file_exists.

If only the file exists, you can use file_exists. file_exists can not only determine whether the file exists, but also determine whether the directory exists. From the function name, we can see that, is_file is used to determine whether the specified path is a file.

More precisely, you can use is_readable and is_writeable to determine whether the file is readable and writable based on the existence of the file.

Delete an object

Similar to Unix commands, PHP uses the unlink function to delete files.

The rmdir function is used to delete a folder. The folder must be empty. If the folder is not empty or has no permission, an error is returned.

Get the file size

You can use the filesize function to obtain the file size, which is expressed by the number of bytes.

If you want to convert the unit of file size, you can define a function.

It is worth noting that the directory size cannot be obtained through simple functions. The directory size is the sum of all subdirectories and file sizes in the directory, therefore, we need to use recursive methods to calculate the directory size cyclically.

Time when the file was modified

Write content to a file

In the preceding example, the $ data parameter can be a one-dimensional array. When $ data is an array, it automatically connects the array, which is equivalent to $ data = implode ('', $ data );

Obtain the current Unix timestamp

Get current date

Obtain the Unix timestamp of the date

PHP provides the built-in function strtotime implementation function: Get the timestamp of a certain date or get the timestamp of a certain time.

Convert formatted date string to Unix Timestamp

The strtotime function is expected to accept a string that contains the American English Date Format and try to parse it into a Unix timestamp.

Format GMT Standard Time

The gmdate function can format the date and time of a GMT and return the Greenwich Mean Time (GMT ).

GD database Overview

GD refers to GraphicDevice. The GD library of PHP is an extension library used to process graphics. Through a series of Apis provided by the GD library, images can be processed or new images can be generated directly.

In addition to text processing, PHP can process JPG, PNG, GIF, SWF, and other images through the GD library. The GD library is commonly used in image watermarking and verification code generation.

Draw lines

Draw text in an image

Use the imagestring function to draw text. Many parameters of this function are: imagestring (resource $ image, int $ font, int $ x, int $ y, string $ s, int $ col), you can use $ font to set the font size, x, y to set the position where the text is displayed, $ s is the text to be drawn, and $ col is the color of the text.

Output Image File

You can use imagepng to save an image as png. If you want to save the image as another format, you need to use different functions to save the image as jpeg, and imagegif to save the image as gif, it must be noted that imagejpeg compresses the image, so you can set a quality parameter.

Generate image Verification Code

Add watermarks to images

Throw an exception

PHP supports Exception Handling starting with PHP5. Exception Handling is an important feature of object-oriented processing. Exceptions in PHP code are thrown by throw. After an exception is thrown, subsequent code will not be executed.

Exception Handling

PHP has many Exception handling classes, of which Exception is the base class for handling all exceptions.

Exception has several basic attributes and methods, including:

Message exception message content

Code Exception code

File Name that throws an exception

Line throws an exception on the number of lines in the file.

Common methods include:

GetTrace

GetTraceAsString string used to obtain exception tracking information

GetMessage

If necessary, you can inherit the Exception class to create a custom Exception handling class.

Capture exception information

Here we only use cases to understand the trycatch mechanism and exception capture methods. In actual applications, exceptions are not thrown easily. Only in extreme or very important situations, will throw an exception, throwing an exception, can ensure the correctness and security of the program, to avoid leading to unpredictable bugs.

Get the row where the error occurred

After an exception is captured, we can obtain the exception information through the exception handling object. We have learned how to capture the exception and obtain basic error information.

In practical applications, we usually get enough exception information and write it into the error log.

We need to record the file name, row number, error information, and exception tracking information of the error to log for debugging and fixing.

Databases supported by PHP

PHP implements database operations by installing corresponding extensions. Modern application design is inseparable from database applications. Currently, mainstream databases include MsSQL, MySQL, Sybase, Db2, Oracle, PostgreSQL, such as Access, PHP can be installed with extensions to support these databases. Generally, the LAMP architecture refers to Linux, Apache, Mysql, PHP, therefore, Mysql databases are widely used in PHP. In this chapter, we will briefly understand the Mysql operation methods.

Database Expansion

A database in PHP may have one or more extensions, either officially or by a third party. Common Mysql extensions include Native mysql databases, enhanced Mysql I extensions, and PDO connections and operations.

Different extensions provide similar operation methods. Different Extensions may have some new features and may have different operation performance.

Insert new data to MySQL

In mysql, after the insert statement is executed, you can obtain the auto-increment primary key id, which can be obtained through the mysql_insert_id function of PHP.

Obtain data query results

Query paging data

Using mysql limit, you can easily implement paging. limitm and n indicate that n rows of data are retrieved from m rows, in PHP, we need to construct m and n to obtain all data on a certain page.

In the above example, we use the $ m and $ n variables to represent the offset and the number of data entries per page. However, we recommend that you use more meaningful variable names, such as $ pagesize, $ start, $ offset, etc. This makes it easier to understand and facilitates collaborative development.

Update and delete data

Data Update and deletion are relatively simple. You only need to build the corresponding SQL statement, and then call mysql_query for execution to complete the corresponding update and deletion operations.

For Delete and update operations, you can use the mysql_affected_rows function to obtain the number of updated data rows. If the data does not change, the result is 0.

Close MySQL connection

After the database operation is complete, you can use mysql_close to close the database connection. By default, when PHP is executed, the database connection is automatically closed.

Mysql_close ();

Although PHP will automatically close the database connection, it generally meets the needs, but in the case of high performance requirements, you can close the database connection as soon as possible after the database operations to save resources, improve performance.

When multiple database connections exist, you can set connection resource parameters to close the specified database connection.

$ Link = mysql_connect ($ host, $ user, $ pass );
Mysql_close ($ link );

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.