SoFunction
Updated on 2025-04-13

PHP/Javascript/CSS/jQuery Common Knowledge Collection Detailed Compilation Page 2/2



            
101. Common Frameworks
       thinkPHP  yii  ZendFramework  CakePhp  sy

102. What is the triggering time for commonly used magic methods?
1) __autoload(): When the program instantiates a class, and the class is not introduced in the current file. The execution of __autoload() will be triggered. The program hopes to automatically introduce this class file through this method. This method has a parameter, that is, the name of the class that you forgot to introduce. What is the working principle of the __autoload() method? When the program executes to instantiate a certain class, if the class file is not introduced before instantiation, the __autoload() function will be automatically executed. This function will find the path of this class file based on the name of the instantiated class. After determining that this class file does exist in the path of this class file, execute include or require to load the class, and then the program continues to execute. If the file does not exist in this path, an error will be prompted. You can use automatically loaded magic functions to write many include or require functions without having to write them.
2) __construct(): This is a magic construction method. The construction method is an automatic method when instantiating an object, and its function is to initialize the object. This method can have no parameters or multiple parameters. If there are parameters, remember to write the corresponding parameters when new object. Before php5, there was no magic constructor. The ordinary constructor was a method with the same name as the class name to implement the constructor. If a class writes both magic constructors and ordinary constructors are defined. Then in the php5 or above versions, the magic method works, and the ordinary constructor does not. On the contrary, in previous versions of php5, the magic constructor method was not recognized, but just regarded this method as an ordinary method.
3) __destruct(): This is a magic destruction method. The function of the destructor method is exactly the opposite of the construction method. It is automatically called when the object is destroyed, and its function is to free memory. The destructor method has no parameters.
4) __call(): When the program calls a non-existent or invisible member method, the execution of __call() is automatically triggered. It has two parameters, namely the method name and the method parameter. The second parameter is the array type.
5) __get(): When the program calls an undefined or invisible member attribute, the execution of __get() is automatically triggered. It has a parameter that indicates the name of the property to be called.
6) __set(): When the program tries to write a non-existent or invisible member attribute, PHP will automatically execute __set(). It contains two parameters, respectively representing the attribute name and attribute value.
7)__tostring(): This method will be called automatically when the program uses echo or print to output objects. The purpose is to convert the object into a string through this method and then output it. __tostring() has no arguments, but the method must have a return value.
8) __clone(): When the program clones an object, the __clone() method can be triggered. The program hopes to implement it through this magic method: not only cloning the object, but also cloned objects need to have all the properties and methods of the original object.

103. What is the concept of MVC?
MVC (i.e., model-view-controller) is a software design model or programming idea invented in the 1980s.
M refers to the model layer, V refers to the view layer (display layer or user interface), and C refers to the control layer.
The purpose of using mvc is to achieve M and V separation, so that a program can easily use different user interfaces.
The purpose of C's existence is to play a regulating role between M and V to ensure synchronization between M and V. Once M changes, V should be able to be updated synchronously.
By separating M and V, you can achieve the same web page and display different page styles when different festivals arrive. This only requires creating multiple view layer template pages in advance.
Without changing the M-layer program.
MVC has achieved division of labor and cooperation in programming, the reusability of the code is maximized, and the program logic is clearer and more organized, making it easier to maintain and manage later.

104. What are the types of access rights modifiers? Comparative explanation
Answer: 1. public means public, and can be called in this class, in subclasses and outside the class.
2. protected means protected and can be called in this class and subclasses.
3. Private means private and can only be called in this class.
4. var, the effect is equivalent to public
105. What modifiers can be found before the Class keyword
a) Final modification means that the class is final and cannot be inherited
b) Abstract modification, indicating that the class is an abstract class

106. In which occasions are the scope operators used
Answer: It is used for the use of operators
a) In this category:
i. self::class constant
ii.
iii.    self:: method()   parent:: method()
b)                                                              �
i. parent::class constant
ii.
iii.    parent:: method() (public or protected)
c)                                                              �
i. Class name::Class constant
ii.
iii. Class name::static method (public)

107. What do $this, self, and parent represent? In which occasions to use
Answer: $this represents the current object. Self represents the current class. Parent represents the parent class of the current class.
Use occasions:
$this can only be used in the current class, and properties and methods in the current class can be called through $this->;
Self can only be used in the current class, and can be accessed through scope operators:: the class constants in the current class, static properties in the current class, and methods in the current class;
Parent can only be used in the current class with the parent class, and access class constants in the parent class, static properties in the parent class, and methods in the parent class through scope operator::.

108. What are the similarities and differences between interfaces and abstract classes?
1. Interface helps PHP to implement multiple inheritance in the functional sense. It uses interface to declare it. Its method has no method body. The implementmens keyword is used to implement the interface.
The interface can only contain abstract methods and class constants, and cannot contain member attributes.
2. An abstract class is a class that cannot be instantiated and can only be a parent class. It is defined by abstract class. There is no difference between abstract class and ordinary class. The class can contain member attributes, class constants, and methods.
Subclasses must be inherited using extends, and they can only be inherited alone.
The similarity between the two is that they cannot be instantiated, they both need to be inherited before they can be used.
The biggest difference between the two is that interfaces can achieve multiple inheritance, while abstract classes can only be single inheritance.
Member attributes cannot be included in the interface, but abstract classes can have member attributes.
The abstract method in the interface must be public or non-access modifiers, and the abstract method in the interface cannot be modified with abstract.
The methods in abstract classes can be ordinary methods or abstract methods. If they are abstract methods, abstract must be used to modify them.

109. Explain the singleton pattern in PHP?
Also known as singleton mode, single element mode, singleton pattern. Singleton pattern refers to creating only one instance of the specified class within the scope of a PHP application. Classes that use singleton patterns are called singleton classes. In PHP, singleton class must have a private constructor, a private magic cloning method (empty in the method body) and a private static member attribute $_instance. The private constructor prevents classes other than itself from instantiating it. A cloning method with empty body of the private method prevents the class from being cloned. $_instance is used to store objects instantiated by itself. There must also be a public static method getInstance(). This method returns the $_instance of the instance object that has been stored.

Singleton: A class can only instantiate one object from beginning to end, and such a class is a singleton class
Advantages of singleton classes: ① Save space ② Save resources
Four key points of implementing singleton classes: ① Private constructor ② Private __clone method ③ Private static attributes, the attributes have public static methods to instantiate objects
Unlimited Classification:
① Database design: region_id (self-increase ID) region_name (region name) parent-id (upper region id) region_path (full path)
②Programming: The function of full path: a. Take data according to the order of full path b. Use it as information hierarchical display.

110. What is SQL injection?
SQL injection attack is one of the common methods used by hackers to attack databases. Some programmers write code,
No judgment is made on the legitimacy of the user's input data. The injector can enter a database query code in the form and submit it.
The program pieced together the submitted information to generate a complete SQL statement, and the server was deceived and executed the malicious SQL command. The injector returns the result according to the program,
Successfully obtaining some sensitive data and even controlling the entire server, this is SQL injection.

111. How to prevent SQL injection?
To filter the submitted information, escape single quotes.
First, you can set it in the mail so that all single quotes are escaped after committing. Or use addslashes().

112. What is the solution to FCKEditor automatic filtering?
If you need to edit the template page, the default FCK setting will remove the <HTML></HTML><BODY></BODY> tag and will add <P></P> tag to you. If you need to keep it, just change the settings.
In it is: = false;
Change to: = true;
If you want to remove the code that automatically adds <P>, you can set it here
The default is
       = 'p' ;    // p | div | br
       = 'br' ; // p | div | br
Change to
       = 'br' ;    // p | div | br
       = 'p' ; // p | div | br

113. The relationship and differences between $_REQUEST, $_GET, $_POST, $_COOKIE:   
1. Relationship: $_REQUEST contains all the contents of $_GET, $_POST, $_COOKIE, etc., and is a collection of them.
2. Get the variable value through $_REQUEST. The PHP page is not sure which way to pass the value,
Therefore, the value will be received according to the configuration in it.
You can set variables_order = "GPC". Its meaning is GET, POST, COOKIE.
So the PHP page will be retrieved from $_GET, then from $_POST, and then from $_COOKIE.
The newly obtained value will overwrite the previously obtained value.
Therefore, from the perspective of expression, $_REQUEST finally gets the value in $_COOKIE. If there is no value in $_COOKIE,
The value in $_POST will be obtained. If $_POST is not obtained, go to $_GET to obtain it.
If there is no value in $_GET, then $_REQUEST returns null.

114. What is multi-condition query (compound query), and how to implement multi-condition query?
How to implement universal query? When querying, you must fill in the query conditions, and these conditions will be submitted through the form.
First, you need to check whether the submitted conditions are empty. If it is not empty, it is considered that this value should be regarded as a condition.
We can use string concatenation to combine an SQL query statement.
Get the query result after execution.

115. What details should be paid attention to when uploading files? How to save files to a specified directory? How to avoid the problem of uploading files with duplicate names?
1). The first appearance is to enable file upload in the file;
2). There is a maximum value that is allowed to upload, and the default is 2MB. Can be changed if necessary;
3). When uploading a form, remember to write enctype="multipart/form-data" in the form tag;
4). The submission method must be post;
5). Set the form control of type="file" and must have the name attribute value;
6). In order to successfully upload, it is necessary to ensure that the size of the uploaded file exceeds the standard, whether the file type meets the requirements, and whether the path stored after upload exists;
7). The form is submitted to the receiving page, and the receiving page uses $_FILES to receive the uploaded files. $_FILES is a multi-dimensional array. The first dimension subscript is the name of the upload control, and the two-dimensional subscripts are name/type/tmp_name/size/error respectively. It represents the file name, file type, temporary file name uploaded to the temporary directory, file size, and whether there are any errors. If it is a batch upload, then the two-dimensional subscript is an array, not a string.
8). After uploading the file, it is placed in the temporary path on the server side. You need to use the move_uploaded_file () function to save the uploaded file to the specified directory.
9). In order to avoid uploading files with duplicate names, you can obtain the file suffix through the uploaded file name, and then rename the file using timestamp + file suffix.

116.     The steps to create an image using the GD2 library?
1). Create a canvas: imagecreate();
2). Set the canvas background color and use RGB to set the color: imagecolorallocate();
3). Set text color: imagecolorallocate();
4). Write text on the canvas: imagestring();
5). Output the image to the browser or file in JPEG format: [Depending on the image format, the functions can also be imagepng(), imagegif(), etc.]   imagejpeg();
6). Clear image resources: imagedestroy();

117.       What are the steps to generate thumbnails in the GD2 library?
1). Read the source image you want to generate thumbnails and create an image object: [The functions are also different depending on the image format]
              $src_image = imagecreatefromjpeg();
2). Get the width and height of the original image $srcW and $srcH, and calculate the width and height of the new image $dstW and $dstH according to the scaling ratio:
3). Create a true color image object, set the width and height to the width and height just calculated:
              $dst_image = imagecreatetruecolor($dstW,$dstH);
4). Copy the image and resize: imagecopyresized();
5). Output the image: [The functions are different depending on the image format] imagejpeg();
6). Clear image resources (clear both the source image resources and the target image resources)   imagedestroy();

118.      How to add a watermark to the picture in the GD2 library?
1. Add a simple text watermark:
Use the imagestring() function to write text watermarks on the image.
2. Add a graphic watermark:
1). Read the source image you want to add a watermark and create an image object: [Depending on the image format, the functions are also different]
                     $image = imagecreatefromjpeg();
2). Create an image object with a watermark image:
                     $watermark = imagecreatefrompng();
3). Copy and merge images:
                     imagecopymerge();
4). Output the image: [The functions are different depending on the image format]
                     imagejpeg();
5). Clear image resources (clear both source image resources and watermark image resources)
                     imagedestroy();

119.       What is a transaction? What is rollback? What is the role of a transaction?
Transactions are several independent SQL operations combined. If one of them fails, then let the combined SQL operations fall back to the unexecution state. This is the rollback of the transaction. The tables of the MyISAM storage engine in mysql do not support transactions. Only the tables of the InnoDB storage engine support transactions. In order for the transaction to execute normally, all data tables participating in the transaction need to be set to the innoDB type. Transactions are wrapped between BEGIN and COMMIT statements. Without using the COMMIT statement, the operation on the database is not permanent and will be rolled back once ROLLBACK is run. Only when COMMIT is executed will the information in the data table be changed. The purpose of a transaction is to ensure the integrity of the data.

120. What is the function of simulating the SESSION mechanism to implement the database to store session data? 【spare】
If the default SESSION mechanism is used, everyone knows that the default SESSION_ID is stored in COOKIE. The user's identity is identified by SESSION_ID. The COOKIE file is stored in the client of the user's browser. This will bring a problem. When the user selects some products to the shopping cart in the office and is preparing to place an order to pay, the user chooses Alipay online payment method. It happens that the office computer does not have Alipay's digital certificate installed, and the user has installed a digital certificate on the user's computer at home, so the user needs to go home to pay. But after going home and logging into the mall, I found that the carefully selected products in the shopping cart no longer exist. Why is this? The problem is that the SESSION_ID cookie file is not stored on the computer at home, so the data in the corresponding session file on the server cannot be correctly read, so the original product information of the selected product is not read. Such shopping cart function gives users a very bad user experience, so we need to use the SESSION mechanism to simulate the SESSION mechanism to use the database to store session data.

121.        What is the Infinitus Classification?
To achieve infinite classification, database table building is the key.
At least three fields are needed in the table structure. If you want to avoid recursive loops, you need four fields.
1. id, the unique identifier of the current data;
2. typename, type name;
3. parentid, the id of the parent type of the previous layer of the current type;
4. path , which stores the id of the current type and the id of all its parent types.
These ids are separated by "-".
5. When it can be implemented through the following sql statements, the information under the same top-level class is displayed in a centralized manner.
select * from table name where condition order by path;
What is the principle of Infinitus classification?
To implement infinite classification, database table structure is the key.
At least three fields are needed in the table structure. If you want to avoid recursive loops, you need four fields.
1. id, the unique identifier of the current data;
2. typename, type name;
3. parentid, the id of the parent type of the previous layer of the current type;
4. path , which stores the id of the current type and the id of all its parent types.
These ids are separated by "-".
5. When it can be implemented through the following sql statements, the information under the same top-level class is displayed in a centralized manner.
select * from table name where condition order by path;

122. What is the principle of paging?
Data paging requires the following conditions:
1. The total number of paging participating [$msg_count], which can be obtained through database query;
2. The number of entries displayed on each page [$pagesize] is defined by yourself;
3. The number of page numbers of the current page [$page], which is passed and received through the address bar;
4. The total number of pages can be calculated through the above information [$pagecount], and ceil() is required here;
              【$pagecount = ceil($msg_count/$pagesize);】
5. Database query uses [limit] in SQL statements to achieve data changes:
For example:
select * from table name where condition limit $startnum , $pagesize;
And $startnum = ($page-1)*$pagesize;

123. How to use php code in smarty template language?
With the help of two smarty built-in functions.
1. The inluce_php function is used to include php scripts in the template. For example:
       {include_php file=""}
2. The php tag allows for the direct embedding of php scripts in the template. For example:
       {php}
echo "This is the function of the built-in function of php";
       {/php}

124. Please list at least five variable regulators in smarty and explain the function?
default  For example: {$arr|default:'xxxx'} , default variable regulator, displays the given default value when the variable is empty
truncate   For example: {$articleTitle|truncate:10}, the length of the cut string is the specified length;
count_characters   For example: {$articleTitle|count_characters}, get the string length;
strip_tags   For example: {$articleTitle|strip_tags} , remove all html tags in the string;
date_format For example: {$|date_format('')} , format the timestamp.

125. The writing program implements the following functions:
a. How to determine whether a character exists in a string?
       echo strstr('abcdefgcd'  , 'cd');
       echo strpos('ab0defgcd'  , 'cd');
b. How to determine the number of times a character appears in a string?
       echo substr_count('abcdefgcd'  , 'cd');
c. How to remove the last character of a string
       echo substr('abcdefgcd'  , 0 ,  -1);

126. How to use smarty's cache and steps? What is single template multiple cache?
If caching is enabled for the entire website, then $smarty->caching=1, the cache time is the default time, that is, 3600 seconds. If you set cache independently for each page, then $smarty->caching=2, the cache time will be linked to the display parameter template page, which means that you can set a different cache time for each template page.
Usage for example:
       if(!$smarty->is_cached('')) {
//The database operations can be performed here
              $smarty->cache_lifetime = 3600*6;
       }
       $smarty->display('');

For pages such as single news, the news template is one. If the cache is enabled, then the cache of all single news pages is one, and the content will not be changed as the id changes. Therefore, in order to distinguish between different page caches, a single template multi-caching technology is needed. The specific method is to use id as the second parameter of display. In addition, for list pages with paging, the second parameter must also be used in display, and the news type id and the current page can be combined into the second parameter.

127. Write a recursive function to complete the following functions: pass a multi-dimensional array into the function and make judgments on all values ​​in the array.
, if the value is 'number', set the value to 0? (Tip: This question tests the application of recursiveness. Because the incoming array is not sure how many dimensions it is, recursive judgment is required)

       function recursive_array($arr) {
              if(is_array($arr)) {
                     foreach($arr as $key=>$value) {
                            if(is_array($value)) {
                                   $arr[$key] = recursive_array($value);
                            } else {
                                   if($value=='number') {
                                          $arr[$key] = '0';                                }
                            }}}
              return $arr;
       }    

 
128. Use jquery to write a selection of all examples?
//Select all and cancel all
       function selectAll(flag) {
              for(var i=0; i<$("#fonds input").size(); i++) {
                     $("#fonds input").get(i).checked=flag;
              }}
//Judge how many check boxes have been checked?
       function checkFonds() {
              var count=0;
              for(var i=0; i<$("#fonds input").size(); i++) {
                     if($("#fonds input").get(i).checked==true) {
                            count++;
                     }}
              alert(count);
       }
//Use descendant selector and get() to get the specified control
       $(“div a”).get(2)

129. Please explain the function of the fetch method in smarty?
The Fetch method can get all the contents of the page and assign it to a variable.
If the fourth parameter is true, it is equivalent to display and output directly to the browser.
If the fourth parameter is false, no output is performed.
The Display method is the fetch method with the fourth parameter true.
       Display = Fetch() + echo()

130. Write out relevant functions about file upload?           
       strrchr($filename , '.');      explode('.' , $filename);
       end($arr);                     strrpos($filename , '.');
       substr($filename , $pos+1);    pathinfo($filename , PATHINFO_EXTENSION);
       date(‘YmdHis')               time()      rand();
       mt_rand()                      move_uploaded_file()

131. How to store SESSION in the database can be combined with the data table design instructions.
By default, session.save_handler = files, that is, session is stored in file form.
If you want to change to a database or other storage method, you need to change the settings and let session.save_handler = user.
In addition to configuring it in the middle, it can also be configured separately in the PHP page, using
ini_set ('session.save_handler, 'user') to set the storage method of session and set it to a user-defined storage method.
After setting up the storage method, you need to use the session_set_save_handler() function.
This function is a function that sets the user-level session saving process. This function has 6 parameters, which are actually the names of 6 custom functions, representing the opening, closing, reading, writing, destroying, and gc (garbage collection) of sessions.
The sample code is as follows:
       function open () { }
       function close() { }
       function read () { }
       function write () {}
       function destroy () {}
       function gc () {}
       session_set_save_handler ("open", "close", "read", "write", "destroy",  "gc");
       session_start();
Now you can use session as usual.
The database structure is as follows:
Session_id , session_value , expire_time , stores the id and value of sessionid and the expiration time respectively.

132. Commonly used regular expression writing methods:
Chinese: /^[\u4E00-\u9FA5]+$/
Mobile phone number: /^(86)?0?1\d{10}$/
       EMAIL:
       /^[\w-]+[\w-.]?@[\w-]+\.{1}[A-Za-z]{2,5}$/
Password (in security level):
       /^(\d+[A-Za-z]\w*|[A-Za-z]+\d\w*)$/
Password (high security level):
       /^(\d+[a-zA-Z~!@#$%^&(){}][\w~!@#$%^&(){}]*|[a-zA-Z~!@#$%^&(){}]+\d[\w~!@#$%^&(){}]*)$/
——————————————————————————
PHP Beginner
——————————————————————————
Order order
var(variables) variable
model typical style model
module module; module; component
enctype
SEO Search Engine Optimization
Search Search
Engine
Optimization optimization, optimization
mod_rewrite module rewrite
CMS content management system
electronic commerce (e-commerce)
gc(garbage collection) garbage collection

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Install
apache (version 2.2) mysql (version 5.067) php (version 5.2)

LAMP Installation under Linux
Responsible for version control SVN
One machine can install multiple apache services, but only one MySQL service can be installed
--------------------------------------------------------------------------------------------------------------------------------
PHP: personal home page Personal home page Version 5.2.6 generated in 1994
ASP: active  server page   93
JSP: java server page

Const is defined in a class called class constants.
Class constants must have initial values
There are three parameters in define('','','false/true'). When it defaults to false, it is case-sensitive, otherwise it is case-insensitive.
It is called a method inside a class. It is called a function outside a class.
Constants are case sensitive by default.
::Scope Operator

The difference between scalar and non-scalar types: scalars can only store one data, while non-scalars can store multiple data
(Properties variable name class constant) case sensitive
(Variable Class Name System-owned Function Custom Function) Case-insensitive
When $_POST['user_name'] and so on are not added, they will be compiled as a constant first.
3. Function
Variable function: The name of the function is a variable
Optional parameters: The parameters have default values
There is a loop body in the body of the recursive function, which calls itself, but it is different from the dead loop. The dead loop has no end. It is an infinite loop, and recursive has an end. He will eventually get a value.
function pager( $page $msg_count $pagesize $url="?"){
}----》$url="?" is the optional parameter

Merge array array_merge()
             $arr1+$arr2
Add two arrays: As long as they have the same subscript, only the first-appearing elements are retained, and the latter is abandoned
array_merge: The index array will append the latter element to the former; if it is an associative array, the same subscript will be used, and the latter will override the former.
exploit() Takes the last element of the array
8. File operation
mkdir new directory
rmdir delete directory
skandir outputs files or directories under the specified path
fopen (resource)—open file or URL
fclose—Close an open file
fgets — read one line at a time
fgetc — Read only one character at a time
fgetss — read one line at a time and filter out HTML tags
file_get_contents — read the entire file into a string
fread-read file
file_put_contents—Write a string to a file
fwrite-write file
unlink-Delete file
pathinfo — Returns the information about the file path
array_push — push one or more cells into the end of an array (to stack)
array_unshift — Insert one or more units at the beginning of an array
9. Other functions
Output control function: ob(output buffer) ob_flush
Encryption function md5
Mathematical function: abs absolute value, rand random number, ceil rounding, floor, mt_rand generate better random number
Conversion function: exploit uses one string to split another string, implode
Time function: date(), strtotime (converts string to timestamp)
Processing address bar: url_encode url_decode
10. Garbage code problem
ASCII (American Standard Code for Information Interchange) was born in 1981
ANSI American National Standards Institute
utf-8 (-8 represents 8 characters at a time) variable byte encoding (3 bytes in Chinese) (utf: Unicode conversion format (UCS Transformation Format)
utf-16 (-16 means 16 characters to be transferred at a time)
GBK. National standard extension code (Guo-Biao Kuozhan) was generated in 90 years (double byte encoding)
GB2312 is ranked 2312 in the international ranking (generated in 1981)
   BIG5
unicode (International encoding) variable byte encoding
   Latin_1
   utf-8+ bom
ISO: International Standardization Organization

11. Database operations
Database optimization: char (fast query speed)
              varchar
Engine: myisam (mysql indexed sequential access method) index order access method
Transaction-supporting engine: BDB, innodb
innodb: It is the trademark of a company starting with inno
The table type is the table storage engine
dll: Dynamic Data Connection Library Encapsulated Class Library

Modifiers: public, var, protected, private, static, final, abstract
Access rights modifiers: public, private, protected
public: There is no restriction on access to class members, and many external members can access it.
protected: Protected and cannot be accessed by external members of the class. The direct subclass of this class can be accessed, and can realize read and write operations on member attributes.
private: Private, only members in the class can access it themselves, and members outside the class cannot access it.
A property is modified as private, so this property cannot be read and modified outside the class. Now there is a way to set the property to be both private and read by external members of the class, namely __get() and __set()

Modifiers to modify class: final, abstract (abstract)
The class that final modified by it cannot be inherited
Defining attributes must be modifiers: they can be public and var
When defining a method, there can be a modifier public, which can be written without writing. The default is public

If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final, it cannot be inherited.
Final can only appear in class classes and methods

There can be public, private, protected, static, final, abstract modifications before the method.
Inheritance: The lower the coupling, the better
Const modification, must have an initial value (smarty's reserved variable: {$},{$},{$},{$},{$},{$},{$},){$}
When calling attributes, if there is $ before, it cannot exist, and if there is $ after, it cannot exist, such as: $this->abc
                                              self::$abc
When parent method is called, the method is automatically converted to static
Polymorphism: caused by inheritance, rewrite (override) (rewrite once) (override rewrite)
PHP does not support overloading (repeated loading), PHP is a weak variable language (overload overload)

Abstract: A class contains abstract methods, which is an abstract class. There are not necessarily abstract methods in abstract classes.
Definition of abstract class abstract
There can be abstract classes in the interface and class constants. An interface can be defined.
When implementing multiple interfaces, the methods in the interface cannot have duplicate names.
All methods defined in an interface must be public, which is a feature of the interface.
Methods in the interface must be rewritten
Static: static cannot coexist with the constructor, static cannot new objects, constructor can new objects, $this cannot be used in the method body

In the previous versions of php5, when the normal constructor and __construct coexist, it will call the normal constructor, which does not recognize __construct (magic method). In the previous versions of php5, when coexist, it will first call __construct (magic method). The destructor method is the last executed and automatically called method
Singleton (singleton)
——————————————————————————
In PHP
——————————————————————————

Includes javascript frameworks and frameworks
Selector:
1. Basic selector:
    ①、$('#result')=jQuery('#result')=('result')
                           <div id='result'>
                        <div class='result'>
②, class selector $('.result')
③, Element selector $('div')
2.Child selector: $('#myform < input')
3. Descendant selector: $('#myform input')
4. Combination selector: $('#myform < span < input')

Ajax is used to asynchronous js and xml. Not only can you get xml data, but you can also get hmtl and json data.
Advantages of ajax: 1. Improve user experience 2. Small bandwidth occupies 3. Reduce server load
ajax displays the content of page B to the specified location of page A to realize asynchronous transmission.
$.ajax() returns the XMLHttpRequest object it created.
   $.ajax({
url:,  data:,  type:,  datatype:,  success:function (In this parameter, all contents of the page being passed back){}   });
$.post('request address','pass parameters','callback function');
$.get('request address','pass parameters','callback function');
There is no size limit for post value transfer files, good confidentiality, and form must be available
Get value transmission is not safe and has size limitations
When there is Chinese in the address bar, use urlencode (encode URL string)
urlencode — Encoding URL string
urldecode (decodes encoded URL string)

4. Session control

session:unset() and array() are deleted together with memory and session file content, and session_destroy just deletes the file
Cookies have no life cycle called session cookies. As the browser closes, the cookies disappear.
There are two ways to exist for cookies, one is to exist in file form, and the other is to be stored in memory.
Only strings can be stored in cookies
Session control is mainly used to pass values ​​across pages
Serialization is to convert other types into string types

Code reuse (include, require, include_once, require_once)
include requires higher performance than require_once include_once
Use require_once(preferably) to load class files.


   dsn(data source name)
//Data source
   $dsn = 'mysql:host=127.0.0.1;dbname=java1008a';
die('end here'); equivalent to echo 'end here';die;

----------------------------------------------------------------------------------

/s and c/s are simply compared, the difference:
--a. Different operating environments (WAN, LAN)
--b, different security levels (low/high)
--c. Different user groups (all users/local users)
--d. Different system upgrades (seamless upgrade/overall upgrade)
--e. Users open different (browser/special software)
--f. Different features of the software interface (information flow/user experience)
For example: b/s is the Weibo and blog online; c/s is the online game played in the Internet cafe (miracle, legend, etc.)
What is: a scripting language running on the server side
--Hypertext Preprocessor
--personal home page
What can language do
--Graphic user interface program
--Run script program on the server side

External variables $_POST[], $_GET[];

Special operators
'.' is the linker
".="is connection assignment
"@" block error message $link=@mySQl_connect(host, username, password)
5. Process control (sequence, selection, loop)
******************************************************************************
******************************************************************************
Unit 3 [String]
1. Three ways to define strings (single quotes, double quotes, and delimiters)
--- Single quote definition (escaping \' and \\)
---Double Quotes Definition (escaping\n\r\t\$\\")
---Delimiter method<<<eof

2. Function part
explode/implode
substr()**
str_replace/trim/ltrim/rtrim

strstr(str, search) gets the content of the specified string that appears at the beginning to the end
strrchr(str, search) gets the content that appears to the last of the specified string
strpos(str, search) gets the initial appearance of the specified string
strrpos(str, search) gets the last occurrence of the specified string
ucfirst(str) capitalizes the first letter of the string
ucwords(str) capitalizes the first letter of each word in a string
strlen(str) gets the string length
strcmp(str1, str2) compares the size of two strings,
Returns a negative number to indicate that str1 is less than str2;
Returns a positive number to indicate that str1 is greater than str2;
Return zero to indicate the same two strings

urlencode(str) replaces all non-alphanumeric characters, becomes % followed by two hexadecimal numbers, and the space becomes + sign
urldecode(str) parses and restores the URL encoded by %##
parse_url(str) parse the complete url transformation into an array
parse_str(str,out) parse request string converted to array
htmlspecialchars() converts html code to entity code
printf/sprintf %b %d %c %x %s %f %X



–     f                                                                                                                                                                                                                                                          �

–     s

–     X                                                          �

1.Array and stack operations
array_push (target array, string) pushes the string into the end of the array
array_pop (target array) pops up the last element of the array and returns
2. Array and queue operations
array_unshift (target array, string) puts the string at the beginning of the array
array_shift (target array) deletes the first element of the array and returns
3. Operation of arrays and pointers key() current() next() prev() reset() end()
4. Predefined array ($_GET $_POST $_FILES $_COOKIE $_SESSION)
******************************************************************************
******************************************************************************
Unit 6 [Other Common Functions]
date(format,[timestamp])//Format the time information and return
time()//Return the current timestamp information

mktime(hour,minute,second,month,day,year)
mktime(hours, minutes, seconds, month, day, year)//Get a Unix time stamp of a date

max()//get maximum value
-echo max(1, 3, 5, 6, 7);  // 7
-echo max(array(2, 4, 5)); // 5
-echo max(0, '1hello');     // 1hello
-echo max('hello', 0);     // hello
-echo max(-1, 'hello');    // hello
-echo max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
-echo max('string', array(2, 5, 7), 42);   // array(2, 5, 7) array and non-array comparison array are always considered to be the largest

mt_rand(65,94)//Get random number
round()//round
flush()//Output content of the preparation area
urlencode('Zhang San')//Returns to the string, all non-alphanumeric parts except -_. are % followed by two digits
Hexadecimal number, space converted to +
urldecode()//Decode the already encoded part
var_dump()//Details of output variables (the data of eight data types can be output)

chr(mt_rand(65,94)) randomly get letters
ord(chr(mt_rand(65,94))) converts letters into numbers
basename (path name) gets the file name part in the path
strtolower converts lowercase

Unit 7 [Php Connection to MySQL]
*mysql_connect(host, username, password) Open a connection to the MySQL server
*mysql_select_db(database, connect to database resources) Select MySQL database
*mysql_query("set names utf8");Set character set
*mysql_close() Close MySQL link
*mysql_query(statement) Send and execute a sql statement
mysql_fetch_row (result resource) obtains a row of results from the result set (index array)
mysql_fetch_assoc (result resource) obtains a row of results from the result set (association array)
*mysql_fetch_array (result resource) obtains a row of results from the result set (index/association array)
mysql_fetch_object(result resource) obtains a row of results from the result set (object array)

mysql_errno() returns the error number
*mysql_error() returns error message
*mysql_num_rows (result resource) is used to calculate the number of rows obtained in the query result
*mysql_affected_rows() gets the number of affected results
*mysql_insert_id() returns the auto-grown ID value generated by the last INSERT instruction

mysql_result (result set, index row, field) specifies to get the result
mysql_free_result(result resource) releases the result set
mysql_num_fields (result resource) is used to calculate the number of columns obtained in the query result
mysql_fetch_field(result resource) obtains the result of the column from the result set and returns it as an object
mysql_pconnect() permanently connects to the database

1. Create a database bbs on the message board and create two tables left_word and back_word (message form and reply form)
  leave_word:
Fields Data Type
id                                                                                                                              �
title     varchar(20) Title
content  text
ittime     datetime    Add time

  back_word:
id                                                                                                                              �
leave_id int
content  text
btime     datetime    Reply time
4. Delete messages and implement the delete function for invalid and useless messages (this time, you need to use get to pass the deleted message id value)
5. Modify the message, and modify it to the required (the deleted message id value is passed by the get method, and then pass it to the receiving page using the hidden domain method)
6. Detailed message display function. Some messages have a lot of content, so it is impossible to display them all on the detailed page (this time, use get to pass the message id)
7. The reply function and reply message display can be realized on the detailed page. Steps: Create a reply form and receive data page.

3. Constructing methods and destructuring methods
Constructor: The first thing you need to do to instantiate an object is the constructor. Before a child is born until he is 5 years old, everything is done by his parents, including naming, dressing, eating, etc.
Destructor: After an object is used, some aftermath work needs to be done. These aftermath work does not require human intervention, such as resource release, variable deletion, etc. For example: After a puppy died, the owner cherished it very much and buried it under a tree in the back garden of his home. The owner did the puppy’s burial, not the dog. This is the destructor.

3. Class rewriting
The thing between a subclass and a parent class is that there are methods of the parent class. The subclass can not only be used directly, but also in the subclass.
Redefine the specific content, for example, if a father can drive a car, then his son can drive a car, but his son
You can drive an airplane without driving a car, this is a rewrite of the type of method.

D     (Last) Keyword Use
Classes modified by this keyword cannot be inherited
The method of modifying this keyword cannot be rewritten
(static) keyword usage (internal, external, subclass of class)
The allocation of instantiated objects in memory involves large data being allocated to the heap space in memory. Now there is an example: there is a
The "Student" class has a member attribute that is "country", which identifies which country the object belongs to, such as the United States, Britain, Germany, etc. When this class instantiates an object, each object will allocate a space in memory to store the member attribute of the country. If
If there are 100 objects, then 100 corresponding spaces will be allocated in the content. If the object of this class is in "China", then
The national attributes of each object will be the same, that is, "China". There will be 100 spaces in memory to store 100 identical contents.
This will cause waste of space. In fact, at this point we can know that 100 identical contents can be stored in one space. Anyway, they are all the same.
This creates the concept of static "static".
A member attribute modified with static, the attribute is not an object, but a class.
Use with parent keywords
Accessing members (properties and methods) in the class inside the class can be used "$this". This keyword refers to objects, which is to access general classes.
Members, if the accessed member is modified with the static keyword, you cannot use "$this" because the class modified with static
Members are owned by the class itself and do not belong to any object. At this time, the "self" keyword needs to be used to modify self:: members.
Accessing members that the class itself outside the class can be accessed in this way. Class name:: member attribute.
Accessing members owned by the parent class in a subclass can use the parent keyword parent:: member attribute
(Constant) keyword usage
Const can be defined in php, defined outside the class with define, and defined inside the class with const.
The owner of the constant is the class itself, and the class uses self::const to access constants inside the class
Use external class access constants Class name::Constant
Subclass access constants parent::constant
6. Use of magic methods clone, __call, __autoload
clone: ​​In a project, we sometimes need two or more exactly the same initialization objects, and we can use clone technology
It is OK without clone technology, but each new object needs to initialize the attribute value, which is more cumbersome and prone to errors.
Using clone is relatively simple. Multiple objects cloned are independent of each other and have nothing to do with each other.
           $p2 = clone $p1;
__call: During the use of the class, if the method called by an object is not in the class, then the program will report an error and then the program will return.
Cannot continue to run if it is released. This is a very bad user experience. If there is a way to make the program report an error, it can continue to run after it is completed.
OK, such a program gives people a better user experience, and you can use __call
             public function __call($method_name,$args){
echo "How to access:";
              echo $method_name;
echo "parameters:";
              print_r($args);
echo "Not exists";
             }
__autoload: When developing a software system, there are often many classes inside. You need to include the pair before initializing the class object.
The corresponding class file. All classes cannot be placed in one file (the file is bloated and difficult to maintain), so that it will be processed
There are many include lists at the beginning of the order, which is very cumbersome to do. If a new class appears, it needs to be included.
Is there a way to make the included class file only be introduced when the object is instantiated, otherwise it will not behave.
The answer is yes, you can use magic method __autoload
                function __autoload($className){
                     include($className.'.php');
                }
8. When a subclass inherits the parent class, member modifier limits, and the modification level of the subclass is greater than that of the parent class. For example, the modifier of the parent class is protected.
Then the subclass modification level is protected or public. The parent class is public, and the subclass must also be public.

1. Abstract Class
A method defined in a class without a method body is an abstract method. Classes with abstract methods are called abstract classes. Abstract classes cannot instantiate objects.
The so-called lack of method body means that the method has no curly braces and contents inside when declaring it.
What is its function:
For example: I have an "animal" type, which has a method to "eat" (there are many other methods)
Animals can have many subclasses, such as dogs, fish, birds, etc. These subclasses have one common feature, that is, they all have the method of eating.
The general solution is: define 3 categories, and there are food methods in it. There is no problem in implementing this, but if one of them is
There is no way to eat, and the program will not report an error at this time. What we have to do now is that any of the 3 categories has no way to eat
The system will report an error. At this time, you need to use abstract classes.
Abstract classes are understood as literally, which is a further abstraction of the three classes. Abstract the way to eat.
Abstract technical characteristics:
a. Abstract classes cannot be instantiated
b. The member methods of the class are abstract, so this class is also abstract.
c. There are no implementation details in the abstract method, and the specific implementation is left to subclass implementation
d. Subclasses that inherit abstract classes must implement abstract classes of the parent class unless they are also abstract classes.

2. Interface (socket example)
When all methods in an abstract class are abstract methods, this abstract class is an "interface".
Interface technical features:
a. Interface statement
b. All interface methods are public, so they can be omitted.
c. The interface only defines methods, no specific methods are implemented
d. Use implements to implement interfaces for implements, and all interface methods must be implemented.
e. The interface can be implemented multiple times, and the middle is separated by commas.
f. Interface is an abstraction of abstract classes. Abstract classes are abstractions of classes, and classes are abstractions of things.
g. The interface cannot be instantiated
(1) What are the differences between abstract classes and interfaces
Abstract classes can only be inherited in a single way, and multiple interfaces can be implemented.
There can be abstract methods and ordinary methods in abstract classes, but there are only abstract methods in interfaces.
Abstract classes can have their own attributes, but only constants can be found in the interface.
The methods in the interface must be public, while the abstract class is different
(2) Similarities between abstract classes and interfaces
The abstract methods in abstract classes must be rewritten when inheriting, and the methods in the interface must also be implemented.
Abstract classes and interfaces cannot be instantiated directly.
Abstract classes need to inherit (extends), and interfaces need to implement (implements).
Both abstract classes and interfaces reflect polymorphic characteristics.


jquery is a package of js. There are many integrated functions for us to use. The purpose of jquery is to write less code to achieve more functions.
Methods to use:
1.Introduce jquery package
              <script type="text/javascript" src='jquery-1.4.'><script>
2. Test whether jquery loaded successfully
              $(function(){
alert("jquey loaded successfully");
              })
3. Get the elements of the page
$('#div'); Get page elements through id
$('.div'); Get page elements through class
Events in jquery
1.$('#mydiv').click(function(){});Mouse click event [to be written in the onload event]
2.$('#mydiv').hover(function(){},function(){}); Move the mouse to the object event
3.$('#mydiv').attr(); Obtain object attribute information
4.$('#mydiv').attr('checked');View the selection of a single check box!
5.$('#mydiv').css(); Obtain the object's attribute information
6.$('#mydiv').css(style, value); assign a style to the object
7.$('#mydiv').addClass('trb'); Assign the value trb to the element class attribute;
8.$('#mydiv').removeClass('trb'); causes the element to lose its class attribute;
9.$('#mydiv').submit(function(){}); Submit event;
10.$('#mydiv').keyup(function(){});Keyboard tapping event;
Use in projects: Verification of forms
Previous page12Read the full text