Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Other aspects of PHP
Other aspects of PHP
PHP's rich support for databases is also one of the reasons for its rapid popularity. It supports the following databases or data files:

Adabas, d, DBA, dBase, dbm, filePro, Informix, InterBase, mSQL, Microsoft SQL Server, MySQL, Solid, Sybase, Oracle, PostgreSQL.

On the internet, it also supports quite a few communication protocols, including IMAP and POP3 network management system SNMP; related to e-mail; Network news NNTP;; ; The account number * * * uses NIS;; ; HTTP and Apache servers of the world wide web; Directory protocol LDAP and other network-related functions.

In addition, CGI programs written in PHP can be easily transplanted to different operating systems. For example, when the system load is too high, a Linux-based website can quickly migrate the whole system to a SUN workstation without recompiling CGI programs. Facing the rapid development of Internet, this is the best choice for long-term planning.

Related grammar and concepts

Php supports eight basic types.

Four scalar types: Boolean integer floating-point (also called "double") string.

Two compound types: array objects.

Finally, there are two special types: resource null.

In order to ensure the readability of the code, this manual also introduces some pseudo types: mixed, number, callback.

Syntax (PHP code boundary characters

There are three syntax for comments: //comment This is a single-line comment /*comment*/ This is a multi-line comment #comment This is a script type comment. Basic structure control statements are rarely used://branch structure (selection structure) if (condition) {//statement} if (condition) {//statement} else {// statement} if (condition) {//statement} else if (condition) {//statement}//. case“value 2”://statement break; Default: //Statement}// loop structure while (condition) {//statement} do {//statement} while (condition); For (initialization; Judge; Change) {//Statement}// Array traverses the special loop statement foreach ($ array as $ value) {echo $ value; } foreach($ Arrayas $ key = & gt; $ value){ echo $ key; Echo $ value} a PHP instance:

The concept of object-oriented programming;

Different authors may have different opinions, but an OOP language must have the following aspects:

1. abstract data types and information encapsulation

2. Legacy

3. Polymorphism

Encapsulation with classes in PHP://In OOP classes, the naming method of big double peaks is usually adopted, and the first letter of each word is capitalized with the class something modifier: public and public * * * private; Protected; //Property names are generally lowercase private $ x = null// In programming suggestions, properties used internally should be given private modifiers and then assigned by methods. //Method names are generally named after small humps, with the first word all lowercase and the rest capitalized. //Because PHP will not automatically use the $this for variable, it is necessary to actively add the $thispseudo variable to point to the operation object publicfunctionsetx ($ v) {$ this-> x = $ v; } publicfunctiongetX(){ return $ this-& gt; x; Of course, you can define it according to your own preferences, but it's better to keep a standard, which will be more effective. Data members are defined by var declarations in classes, and they are untyped until they are assigned values. Data members can be integers, arrays, associative arrays or objects. Methods are defined as functions in a class. When accessing class member variables in methods, you should use $ this->; Name, otherwise it can only be a local variable for a method.

Use the new operator to create an object: $ obj = newSomething, and then you can use the member function to pass: $ obj-& gt;; setX(5); $ see = $ obj-& gt; getX(); Echo $ see In this example, the setX member function assigns 5 to the member variable x of an object (not a class), and then getX returns its value of 5. Can be like: $ obj-& gt;; It is not a good OOP habit to access data members through class references when x=6. I strongly recommend accessing member variables through the method. If you treat member variables as unhandled and use methods only through object handles, you will be an excellent OOP programmer. Unfortunately, PHP does not support declaring private member variables, so bad code is allowed in PHP. As long as you use the extends keyword, inheritance is easy to implement in PHP. class another extends something { private $ y; publicfunctionsetY($ v){ $ this-& gt; y = $ v; } function gety(){ return $ this-& gt; y; }} The object of another class owns all the data members and methods of the parent class, and also adds its own data members and methods.

You can use $ obj2 = new another $ obj2->; setY(5); echo $ obj 2-& gt; getY(); PHP only supports single inheritance, so you can't derive new classes from two or more classes. You can redefine methods in derived classes. If we redefine the getX method in another class (method rewriting), we can't use the getX method in something. If a data member with the same name as the base class is declared in a derived class, it will "hide" the data member of the base class when it is processed.

You can define constructors in a class. The constructor is a method with the same name as the class name, which will be called when you create an object of a class. For example, the new version of the constructor abandons the class name and uses the public function _ _ construct () _ _ construct ($ x) {$ this->; x = $ x} publicfunctionsetX($ v){ $ this-& gt; x = $ v; } publicfunctiongetX(){ return $ this-& gt; x; }//destructor public function _ _ destroy () {} So that an object can be created by: $ $obj=newSomething(6); (6); The constructor will automatically assign a value of 6 to the data variable X. Constructors and methods are ordinary PHP functions ("_ _" two underscores, magic method), so the default parameters can be used. Public function _ _ construct ($ x = 3,$ y = 5){ } Then:$ obj = new something(); //x = 3 Andy = 5 $ obj = new something(8); //x=8andy=5$obj=newSomething(8,9); //x=8andy=9 The default parameter is in the form of C++, so you can't ignore the value of Y. Give X a default parameter and assign values from left to right. If the passed-in parameter is less than the required parameter, the default parameter will be used.

When creating an object of a derived class, only its constructor is called, not the constructor of the parent class. If you want to call the constructor of the base class, you must use parent::__construct () in the constructor of the derived class. What you can do is that all parent methods are available in derived classes. class anotherextendsomething { public function _ _ construct(){ parent::_ _ construct(5,6); //A good mechanism for calling the base class constructor }}OOP is to use abstract classes. Abstract classes cannot be instantiated, and only an interface can be provided for derived classes. Designers usually use abstract classes to force programmers to derive from base classes, which can ensure that new classes contain some expected functions. There is no standard method in PHP, but if you need this feature, you can define the base class, add the call of die after its constructor, so as to ensure that the base class cannot be instantiated, and add the die statement after each method (interface), so that if the programmer does not rewrite the method in the derived class, it will lead to an error. And because PHP is untyped, you may need to confirm that an object is derived from your base class, so add a method to the base class to clarify the identity of the class (return some kind of identification id) and check this value when you receive the object parameters. Of course, if a bad evil programmer rewrites this method in a derived class, this method will not work, but the common problem is that there are more lazy programmers than evil programmers.

Of course, it's good for programmers not to see the base class. Just print out the interface and do their job well. PHP 5 introduces the concept of destructor, which is similar to other object-oriented languages, such as C++. When all references to an object are deleted or the object is explicitly destroyed, the destructor is executed.

PHP does not support overloading (unlike overwriting) because PHP is a weakly typed language. In OOP, you can overload a method to realize that two or more methods have the same name, but the number or type of parameters are different (depending on the language). PHP is a loosely typed language, so overloading by type doesn't work, but overloading by different numbers of parameters doesn't work either.

Sometimes it is very good to overload constructors in OOP, so that you can create objects (variable functions) in different ways. The skills to realize in PHP are: class my class {publicfunctionmyclass () {$ name = my class. func _ num _ args()。 //This function returns the number of passed parameters $ this->; $ name(); //A variable function is used here, and the value of this variable is called as the function name} PublicFunctionMyClass1($ x) {/code} PublicFunctionMyClass2 ($ x, $ y) {/code}} Through extra processing in the class, using this class is transparent to users: $ obj60. //myclass1$ obj2 = newmyclass ('1','2') will be called; //Myclass2 will be called. Sometimes this is very useful.

polymorphic

Polymorphism is the ability of an object to decide which object's method to call according to the passed object parameters at runtime. For example, if you have a graphics class, it defines a drawing method. And derive circular and rectangular classes. In a derived class, you override the draw method, and you may have a function that wants to use the parameter x and can call $ x->; Draw (). If you are polymorphic, which draw method to call depends on the object type you pass to this function.

Polymorphism in interpreted languages such as PHP (imagine a C++ compiler generating such code, which method should be called? You don't know what kind of person you have, well, that's not the point. It's easy and natural. So PHP certainly supports polymorphism. Classcalc {functionnicedrawing ($ x) {//Suppose this is a method of Board class $ x->; draw(); }} ClassCircle {PublicFuncodraw () {Echo drew a circle; }} ClassRectangle {PublicFuncodraw () {Echo drew a rectangle; } } $ board = newCalc$obj=newCircle(3, 187); $obj2=newRectangle(4,5); $ board->; nice drawing($ obj); //Circle's draw method $ board- > will be called. nice drawing($ obj 2); PHP object-oriented programming will call Rectangle's draw method.

Admittedly, some purists may say that PHP is not a real object-oriented language. PHP is a mixed language. You can use OOP or traditional procedural programming. However, for large projects, you may want/need to declare classes in PHP with pure OOP, and only use objects and classes in your project.

As the project gets bigger and bigger, using OOP may help. OOP code is easy to maintain, understand and reuse. These are the foundations of software engineering. Applying these concepts to web-based projects will be the key to the success of future websites.

Advanced object-oriented technology

After reading the basic OOP concepts, I can show you more advanced technologies:

Serialization (serialization)

PHP does not support persistent objects. In OOP, persistent objects are objects that can maintain their state and function in references of multiple applications, which means that they have the ability to save objects to files or databases, and they can be loaded later. This is called serialization mechanism. PHP has a serialization method that can be called through an object, and the serialization method can return a string representation of the object. However, serialization only saves the member data of the object, not including the method.

In PHP4, if you serialize the object into the string $s, then release the object and deserialize it into $obj, you can continue to use the object method! I don't recommend this, because (a) there is no guarantee in the document that this behavior can still be used in future versions. (b) This may lead to misunderstanding when you save the serialized version to disk and exit the script. When you run this script later, you can't expect that when you deserialize an object, its methods will also be there, because the string representation doesn't include methods at all.

In short, PHP serialization is very useful for saving member variables of an object. You can also serialize related arrays and arrays into a file.

Example: $ obj = new classfoo (); $ str = serialize($ obj); //Save $str to disk $ obj2 = unserialize ($ str); //After a few months//loading str from disk, you recover the member data, but not including the method (according to the document). This leads to the only way to solve this problem is to use $ obj 2->; X to access member variables (you have no other way! ), so don't try it at home.

There are some ways to solve this problem, and I will keep them, because they are too bad for this concise article. I am happy to welcome the full serialization feature in subsequent versions of PHP.

A very good thing about using classes to store data in PHP and OOP is that you can easily define a class to operate something, and you can call the corresponding class when you want to use it. Suppose you have an HTML form, and users can select products by selecting their product ID numbers. There is product information in the database. You want to display the product, its price and so on. You have different types of products, and the same action may have different meanings for different products. For example, displaying sound may mean playing it, but for other types of products, it may mean displaying pictures stored in a database. You can use OOP or PHP to reduce coding and improve quality:

Define the class of a product, define the methods it should have (such as display), and then define the classes of each product, which are all derived from the product class (SoundItem class, ViewableItem class, etc.). ) and cover the methods in the product category to make them act according to your ideas.

The class is named according to the type field of each product in the database. A typical product list may have (id, type, price, description, etc. ) ... and then in the processing script, you can take out the type value from the database and instantiate an object named type: $obj=new$type (); $ obj-& gt; action(); This is a very good feature of PHP. Regardless of the type of the object, you can call the display method of $obj or other methods. With this technology, you don't need to modify the script to add a new type of object, just add a class to handle it.

This function is very powerful. As long as you define methods, regardless of all object types, implement them in different ways in different classes, and then use them on any object in the main script, there is no if ... else, and you don't need two programmers, just be happy.

Do you agree that programming is easy, maintenance is cheap and reusable?

If you manage a group of programmers, assigning work is very simple. Everyone may be responsible for a type of object and the class that handles it.

Through this technology, internationalization can be realized, and corresponding classes can be applied according to the language field selected by users, and so on.

Replication and cloning

When creating an object of $obj, you can copy the object by $obj2=$obj. The new object is a copy of $obj (not a reference), so it has the status of $obj at that time. Sometimes, you don't want to do this. You just want to generate a new object like the obj class. You can use the new statement to call the constructor of the class. It can also be implemented through serialization and base classes in PHP, but all other classes must be derived from the base class.

Enter the dangerous area

When you serialize an object, you get a string in a specific format. If you are interested, you can study it, and the string contains the name of the class (great! ), you can take it out, for example: $ herring = serialize ($ obj); $vec=explode(':',$ herring); //Split the string into an array with: as the identifier $nam=str_replace(\,'', $ vec [2]); So suppose you create a class of the universe and force all classes to extend from the universe, you can define a clone method in the Universe as follows: Class Universe {//cloning (_ _ clone ()) in the new PHP version is a magical method, not to be confused with the function clone () {$ herring = serialize ($ this). $vec=explode(':',$ herring); $nam=str_replace(\,'',$ vec[2]); $ ret = new $ nam returns $ ret} }// and then $ obj = new something (); //Extend $ other = $ obj-& gt; clone(); What you get is a new object of Something class, which is the same as the object created by using the new method and calling the constructor. I don't know if this is useful to you, but it's a good experience for the universe class to know the names of derived classes. Imagination is the only limit.

The template engine Smarty:Smarty is characterized by compiling templates into PHP scripts and then executing these scripts. Soon, very convenient. Heyes Template Class: A very easy-to-use but powerful and fast template engine that helps you separate page layout and design from code. FastTemplate: A simple variable interpolation template class that analyzes your template and separates variable values from HTML code. ShellPage: an easy-to-use class that allows your entire website layout to be based on template files. Modifying the template can change the whole website. STP Simple Template Parser: A simple, lightweight and easy-to-use template analysis class. It can assemble a page from multiple templates and output the resulting page to a browser or file system. OO template class: an object-oriented template class that can be used in your own programs. SimpleTemplate: a template engine that can create and structure websites. It can parse and compile templates. BTemplate: a short but fast template class that allows you to separate PHP logic code from HTML decoration code. Savant: A powerful lightweight PEAR-compatible template system. It is non-compiled and uses PHP itself as its template language. ETS-easy template system: A template system that can reorganize templates with exactly the same data. EasyTemplatePHP: a simple but powerful website template system. VlibTemplate: A fast and universal template system, including a caching and debugging class. AvanTemplate: multi-byte security template engine, occupying less system resources. Variable substitution is supported, and the content block can be set to show or hide the fasttemplate of Grafx software: a modified version of the fasttemplate system, including caching function, debugging console and mute removal as assignment blocks. TemplatePower: A fast, simple and powerful template class. The main function is nested dynamic block support, and the block/file contains support and shows/hides unallocated variables. TagTemplate: The function of this library is designed to use template files and allow you to retrieve information from HTML files. Htmltmpl: template engine: template engine for Python and PHP. It is aimed at web application developers who want to separate code and design in their projects. Php class for parsing Dreamweaver templates: A simple class for parsing Dreamweaver templates, used in the custom modules of Gallery 2 and WordPress. Minitemplate engine: a compact template engine for HTML files. It has simple syntax for template variables and block definitions. Where blocks can be nested. Layout solution: Simplify website development and maintenance. It has common variables and page elements, so you don't have to do the work of page layout repeatedly. Cache FastTemplate: it has been incorporated into Fast Template, allowing you to cache template files and even cache different specifications on individual block contents. TinyButStrong: a template engine that supports MySQL, Odbc, Sql-Server and ADODB. It contains seven methods and two properties. Brian Lozier's PHP-based template engine: only 2K in size, very fast and object-oriented. WACT: A template engine that separates code from design. Phptal: an XML/XHTML template library under PHP. Rong _ View _ Invincible Beauty: The template engine of domestic frameworks developed by Invincible Beauty is similar to smarty, with the advantage of high speed and the disadvantage of few template tags, but it is enough. Framework introduction thinkphp

ThinkPHP is a free, open source, fast and simple object-oriented lightweight PHP development framework, which was founded in early 2006 and released according to Apache2 open source protocol, and was born for agile WEB application development and simplified enterprise application development. ThinkPHP has been adhering to the simple and practical design principle since its birth, paying attention to ease of use while maintaining excellent performance and minimal code. And it has many original functions and features. With the active participation of the community team, it has been continuously optimized and improved in terms of usability, expansibility and performance. It has grown into the most advanced and influential WEB application development framework in China, and many typical cases are guaranteed to be stably used for commercial and portal-level development.

PHP certification level

The PHP course consists of three parts: elementary (IFE), intermediate (IPE) and advanced (IAE). IFE is the abbreviation of Index front-end engineer, which means index front-end engineer. IPE is the abbreviation of Index PHP Engineer, which means index PHP engineer. IAE is the abbreviation of index architecture/senior engineer, which means: index senior/architectural engineer. PHP security

In fact, PHP is only a module function of the Web server, so the security of the Web server must be guaranteed first. Of course, if the Web server wants to be secure, it must first ensure the security of the system, which is far-fetched and endless. Common web security vulnerabilities include: injection attacks, cross-site attacks, server vulnerabilities and so on. For a detailed explanation, please refer to "Web Security-2065438+00 _ OWASP _ top10" in the extended reading, which has a very detailed explanation.

Advantages of PHP learning process and method

The syntax of PHP is similar to C, Perl, ASP or JSP. PHP is too simple for people who are familiar with one of the above languages. On the contrary, if you know more about PHP, you can easily learn several other languages. You only need to master all the core language features of PHP in a short time. You may already know HTML very well, and even you already know how to make beautiful websites by editing and designing software or by hand. Because PHP code can be added to your site without obstacles, you can easily add PHP to make your site more dynamic when designing and maintaining your site.

Database connection

PHP can be compiled with functions connected to many databases. PHP and MySQL are an excellent combination, and if you add Apache server, it will be quite perfect. You can also write your own peripheral functions to access the database indirectly. In this way, when you change the database you use, you can easily change the encoding to adapt to this change. PHPLIB is the most commonly used basic library, which can provide general transaction requirements.

expansibility

As mentioned earlier, PHP has entered a period of rapid development. It may be difficult for a non-programmer to extend the additional functions of PHP, but it is not difficult for a PHP programmer.

PHP scalability

Traditionally, the interaction of web pages is realized through CGI. The scalability of CGI programs is not ideal because it opens an independent process for each running CGI program. The solution is to compile interpreters (such as mod_perl, JSP) of languages that are often used to write CGI programs. PHP can be installed like this, although few people want to install it in CGI like this. Embedded PHP is more extensible.

PHP free installation

PHP source code package installation version: This version is suitable for professional website construction users who already have their own independent website domain name and website space. The use method is still simple, only three steps are needed:

First of all, go to official website: download the latest version of the installed PHP source code package, decompress the downloaded files, and upload all the contents to your website space that supports PHP.

2. To change the file attributes, please change the files with PHP suffix in the root directory, folders "/include/domain.php" and "/attachments"/"data" and all the file attributes under the folders to "readable", "writable" and "executable", usually "755".

Third, open the root directory of your website, and the system will automatically run the setup installer, and click Next according to the prompt.

Friendly reminder: when you download our software and see this description, it means that you must have certain needs for enterprise website construction, or you are a website construction technology learner.

File format for files that only contain php code, we will ignore it at the end of the file? & gt。 This is to prevent extra spaces or other characters from affecting the code. For example:

The indentation of $ foo =' foo should reflect the logical result of the code. Try to use four spaces. Tabbing is forbidden because it can ensure the flexibility of cross-client programmer software. For example: if (1= = $ x) {$ indexed _ code =1; if( 1 = = $ new _ line){ $ more _ indented _ code = 1; It is recommended to keep equal spacing and arrangement for variable assignment. For example: $ variable =' demo$ var =' demo2 The length of each line of code should be controlled within 80 characters, and the maximum length should not exceed 120 characters. Because the file read by linux is 80 columns, that is to say, if a line of code exceeds 80 characters, the system will pay extra instructions for it. Although this seems to be a small problem, it is also a norm worthy of attention and compliance for programmers who pursue perfection. No extra spaces are allowed at the end of each line. The problem of garbled editing in Php file notepad

Generally speaking, when Notepad Editor finishes editing and saving files, its default encoding is ANSI and Chinese. However, more often, the language of php is utf-8 when setting the language environment, and it will be garbled when it is directly saved for http-server parsing such as apache.

Therefore, it should be noted that after editing with Notepad, the file can be saved as "Save As", the file type should be "All Files", and the encoding should be consistent with the language encoding specified in the file.

arithmetic operator

PHP operators include arithmetic operators, assignment operators, comparison operators and logical operators.

Arithmetic operator:

Addition, subtraction, multiplication, division, modulus (remainder)+,-,*,/,%

Assignment operator: (The following explanation is different in many books)

Assignment, addition assignment, subtraction assignment, multiplication assignment, division assignment and hyphenation assignment.

=、+=、-=、*=、/=、.=

Bit operator:

Bit AND, bit OR, bit OR, bit NOT, left shift, right shift.

& amp、|、^、~、<; & lt、gt; & gt

Comparison operator:

Equal to, completely equal to, not equal to, not completely equal to, greater than, less than, greater than or equal to, less than or equal to.

==、===、! =(& lt; & gt)、! == 、& gt、& lt、gt; = 、& lt=

Logical operator:

Logical AND, logical OR, logical NOT, logical OR

& amp& amp、||、! XOR

String operator:

. Concatenates two strings.