It is not easy to become a PHP programming expert. As many people think, as long as they can quickly write a few simple codes to solve a complicated title, they are PHP programmers, real PHP experts also need to consider other titles. The following three principles should be followed by a mature PHP programmer in programming.
PHP is an efficient network programming language. due to its advantages in mobile programming and fast running, Agility has become the preferred language for Web programmers. A recent authoritative survey showed that 31.6% of websites now use PHP as an important server programming language.
However, it is not easy to become a PHP programming expert. As many people think, as long as they can quickly write a few simple codes to solve a complicated title, they are PHP programmers, real PHP experts also need to consider other titles. The following three principles should be followed by a mature PHP programmer in programming.
1. laziness is gold
2. write beautiful code
3. seek the speed of the program, not the speed of programming
1. laziness is gold
Is it an idle programmer? This idea is amazing! The busiest people in the world may be computer programmers. But it is because programmers are too busy that they should learn to be lazy during programming.
For a programmer, there are two ways of laziness: first, brave application of ready-made others' program code to integrate the code into your own program or project. The second is to write some useful code to create a function library, which can be easily written in the future, saving a lot of repetitive work. Naturally, you can be idle.
Both of these methods are very suitable for PHP programmers.
First, PHP is a language born and grown up in a free and open environment. There are thousands of programmers around the world who have been constantly striving for PHP perfection and are willing to share their talents and code with others. Every day, you can create a large number of excellent program codes from some PHP websites, email lists, and message groups. In this way, I do not encourage you to wait all day for others to write code for you, but you can "stand on the shoulders of great people" and fully carry forward "ism ", intelligent use of others' program code can save you a lot of time. Second, in PHP, you can easily create your own function library, which saves you a lot of trouble in programming later.
Below I will introduce several common functions for you. some of these functions come from some open source projects on the Internet, and some are selected from the mail list. If you can add them to your own function library, sooner or later you will invent yourself and enjoy unlimited benefits.
1. common database processing functions
Compared with other CGI functions, one of the strengths of PHP is its strong ability to process databases. However, in PHP, some specific functions are applied to different databases for special processing, and there is a lack of common database processing functions. This greatly reduces the portability of program code, which also brings a lot of inconvenience to beginners.
On the Internet, many programmers solve this title by encapsulating classes. They have compiled the same function to deal with any popular database-Mysql, which is popular in the Linux world, or SqlServer, which is widely used on Windows platforms. In my personal opinion, I am very fond of using these functions, because some simple functions such as 'query' and 'Next _ record 'can be applied directly, you do not need to consider the complex things such as database connection and database handle, and do not need to consider what type of database is used.
2. variable debugging functions
Debugging PHP programs has always been a headache. it does not have an integrated compilation and debugging environment like other advanced languages such as VB, and do not want Perl to run in a Linux or DOS environment. Actually, we can use echo statements to complete PHP debugging.
The following functions allow you to view the types and values of any variables in the program at any time.
Function ss_array_as_string (& $ array, $ column = 0 ){
$ Str = 'Array (
N ';
While (list ($ var, $ val) = each ($ array )){
For ($ I = 0; $ I <$ column + 1; $ I ++ ){
$ Str. = '& nbsp ;';
}
$ Str. = $ var. =>;
$ Str. = ss_as_string ($ val, $ column + 1 ).'
N ';
}
For ($ I = 0; $ I <$ column; $ I ++ ){
$ Str. = '& nbsp ;';
}
Return $ str .);
}
Function ss_object_as_string (& $ object, $ column = 0 ){
If (empty ($ object-> classname )){
Return '$ object ';
}
Else {
$ Str = $ object-> classname .'(
N ';
While (list (, $ var) = each ($ object-> persistent_slots )){
For ($ I = 0; $ I <$ column; $ I ++ ){
$ Str. = '& nbsp ;';
}
Global $ var;
$ Str. = $ var. =>;
$ Str. = ss_as_string ($ var, column + 1 ).'
N ';
}
For ($ I = 0; $ I <$ column; $ I ++ ){
$ Str. = '& nbsp ;';
}
Return $ str .);
}
}
Function ss_as_string (& $ thing, $ column = 0 ){
If (is_object ($ thing )){
Return ss_object_as_string ($ thing, $ column );
}
Elseif (is_array ($ thing )){
Return ss_array_as_string ($ thing, $ column );
}
Elseif (is_double ($ thing )){
Return 'double ('. $ thing .')';
}
Elseif (is_long ($ thing )){
Return 'long ('. $ thing .')';
}
Elseif (is_string ($ thing )){
Return 'string ('. $ thing .')';
}
Else {
Return 'unknown ('. $ thing .')';
}
}
When necessary, simply add the following code to the program to view the type and value of the variables (including arrays and objects) applied in the program:
Echo ss_as_string ($ my_variable );
Using the following statement, we can directly view the values of all the variables in the program:
Echo ss_as_string ($ GLOBALS );
3. functions that hold Log information
Another important method for debugging PHP programs is to view Log information. If you can easily control the Log information level and the Log information display content, it will bring more convenience to program debugging. The following functions can achieve this function easily.
$ Ss_log_level = 0;
$ Ss_log_filename =/tmp/ss-log;
$ Ss_log_levels = array (
NONE => 0,
ERROR => 1,
INFO => 2,
DEBUG => 3 );
Function ss_log_set_level ($ level = ERROR ){
Global $ ss_log_level;
$ Ss_log_level = $ level;
}
Function ss_log ($ level, $ message ){
Global $ ss_log_level, $ ss-log-filename;
If ($ ss_log_levels [$ ss_log_level] <$ ss_log_levels [$ level]) {
// Do not display Log information
Return false;
}
$ Fd = fopen ($ ss_log_filename, 'A + ');
Fputs ($ fd, $ level.-[. ss_timestamp_pretty ().]-. $ message. 'N ');
Fclose ($ fd );
Return true;
}
Function ss_log_reset (){
Global $ ss_log_filename;
@ Unlink ($ ss_log_filename );
}
In the above function, there are four Log-level variables. When running a PHP program, the Log information can be recorded and displayed only when the Log level is lower than the preset level value. For example, add the following statement to the program:
Ss_log_set_level (INFO );
When running a PHP program, only the LOG information at the ERROR and INFO level can be recorded and displayed, while the DEBUG level information is neglected. In addition, you can set the displayed information. The statement is as follows:
Ss_log (ERROR, 'testing level error ');
Ss_log (INFO, 'testing level info ');
Ss_log (DEBUG, 'testing level debug ');
You can also use the following statement to clear LOG information at any time:
Ss_log_reset ();
4. speed test functions
To optimize the code, we need a method that can test the code running time to select the best code. The following function can test the time required to run the code:
Function ss_timing_start ($ name = default ){
Global $ ss_timing_start_times;
$ Ss_timing_start_times [$ name] = explode (, microtime ());
}
Function ss_timing_stop ($ name = default ){
Global $ ss_timing_stop_times;
$ Ss_timing_stop_times [$ name] = explode (, microtime ());
}
Function ss_timing_current ($ name = default ){
Global $ ss_timing_start_times, $ ss_timing_stop_times;
If (! Isset ($ ss_timing_start_times [$ name]) {
Return 0;
}
If (! Isset ($ ss_timing_stop_times [$ name]) {
$ Stop_time = explode (, microtime ());
}
Else {
$ Stop_time = $ ss_timing_stop_times [$ name];
}
$ Current = $ stop_time [1]-$ ss_timing_start_times [$ name] [1];
$ Current + = $ stop_time [0]-$ ss_timing_start_times [$ name] [0];
Return $ current;
}
Now we can easily check the performance time of any piece of code. we can even apply multiple timers at the same time, you only need to set different parameters as the timer name when applying the preceding functions.
5. debug and optimize database control
For databases, the running speed is crucial. Although many books and articles have explained some methods to quickly run databases, all methods must be tested in practice. Next, we will combine the query () function in the PHPLib function library with the above-mentioned functions to compile a new query () function. compared with the original function, this function increases the monitoring performance of running time.
Function query ($ Query_String, $ halt_on_error = 1 ){
$ This-> connect ();
Ss_timing_start ();
$ This-> Query_ID = @ mysql_query ($ Query_String, $ this-> Link_ID );
Ss_timing_stop ();
Ss_log (INFO, ss_timing_current (). Secs-. $ Query_String );
$ This-> Row = 0;
$ This-> Errno = mysql_errno ();
$ This-> Error = mysql_error ();
If ($ halt_on_error &&! $ This-> Query_ID ){
$ This-> halt ('invalid SQL: '. $ Query_String );
}
Return $ this-> Query_ID;
}
2. write beautiful code
1. leave the background program and the front-end program
When writing a PHP program, some code is used to process some transactions, such as holding the database and performing mathematical operations. other code is only displayed as the result of transaction processing, for example, some application echo statements display the results in the HTML format on the Web browser PHP code and those directly embedded in the PHP program HTML code. First, we should understand the two types of code. The former is called a background program and the latter is called a frontend program.
Because PHP is an embedded programming language, that is to say, all PHP code can be embedded into HTML code, which brings a lot of convenience for programming. However, if PHP code and HTML code are mixed in a long program, this will make the program messy, not conducive to program protection and browsing. Therefore, we need to try to port the PHP code in these programs mixed with HTML code, and encapsulate the code into a function in a special file, then, you can apply the include statement in the HTML code to include these files and call these functions as appropriate.
On the one hand, this method makes HTML code and PHP code both simple and easy to read. on the other hand, because HTML code needs to be constantly updated, this method can ensure that the background program will not be damaged.
Different from front-end programs, background programs are more seeking for stability, structure, and few changes. Therefore, they should be carefully designed and managed. In fact, it is worthwhile to invest a large amount of time in the design of a program. "Planting trees now and enjoying the cold in the future" will allow you to easily apply the background program you have prepared in future design work.
2. mobile app inclusion files
As mentioned above, background programs should be arranged in a series of include files. Include files can be dynamically loaded as needed through the include statement, or in the php. ini file by applying the auto_prepend_file command in advance.
If we use the latter method, we will certainly achieve the benefits once and for all, but there are also some problems worth noting. The following code shows us how long it takes to analyze a large file:
Require (timing. inc );
Ss_timing_start ();
Include (test. inc );
Ss_timing_stop ();
Echo
. Ss_timing_current ().
;
?>
In the above code, test. inc is a 1000-row file. it takes 0.6 seconds to parse the file. for a large website, this speed is not negligible.
Another problem with an application containing files is that if a statement in a file produces an error, PHP programs on all websites will not be able to run. Therefore, we are also vigilant when it is used.
Actually, the inclusion file can be parsed only when necessary. The following code parses the abc. inc file only when the program needs it:
If (defined (_ LIBA_INC) return;
Define (_ LIBA_INC, 1 );
/*
* Code...
*/
?>
3. application object-oriented programming method
PHP is also an object-oriented language. the object-oriented programming method is a software design method that excellent programmers are very careful, in PHP programming, the advantages of object-oriented language can be fully applied to encapsulate the objects in programming. In the previous code, we applied object-oriented methods. for example, when we managed the database, we encapsulated the query () function into the database class, which greatly facilitated code governance, added the readability of the program.
3. SEEK program speed, not programming speed
During website construction, the program running speed and website download speed are important factors that affect the success or failure of the website. As a Web programmer, you should pay more attention to the code running speed. The following methods increase the code running speed to different degrees.
1. use embedded HTML code instead of PHP echo statements.
As PHP is an embedded Web programming language, HTML code and PHP code can be embedded into each other. However, many programmers worry that too many applications of ''in HTML code will call the PHP interpreter multiple times, reducing the PHP code running speed, therefore, we prefer to use PHP echo statements to output HTML code without directly applying HTML code. But the opposite is true. Every PHP page only calls the PHP interpreter once to describe all the PHP code. Therefore, the PHP code is embedded only when necessary, and most of the time the HTML code is directly applied to the result, this will not only reduce the program running speed, but also reduce the resolution of echo statements, which can often improve the code running speed.
The following code confirms our conclusion. In this code, we applied the time-tested function previously introduced.
Apply str-replace instead of ereg-replace
Programmers who are used to programming with Perl are more willing to use ereg_replace to complete string replacement, because the usage of ereg_replace in PHP is similar to that of pattern matching in Perl. However, the following code confirms that replacing ereg_replace with str_replace can greatly improve the code running speed.
Test the running speed of str_replace and ereg_replace
// This code tests the running speed of str_replace.
Emphasis;?>
For ($ I = 0; I I <1000; $ I ++ ){
Str_replace (I>, B>, $ string ).
;
}
?>
// This code tests the running speed of ereg_replace.
For ($ I = 0; I I <1000; $ I ++ ){
Ereg_replace (<([/] *) I >,< \ 1b>, $ string ).
;
}
?>
// Print the result
Conclusion
Time when str_replace is applied-
Time when ereg_pattern is applied-
Run the above code and the result is:
Time when str_replace is applied-0.089757
Time when ereg_pattern is applied-0.248881
From the running results, we can see that the application str_replace replaces ereg_replace as a string replacement function, greatly improving the code running speed.
3. pay attention to string references.
Like many other programming languages, PHP can use double quotation marks ('') to reference strings, or single quotation marks (). However, in PHP, if double quotation marks are used to reference a string, the PHP parser first analyzes whether there is any reference to the variable in the string. if there is a variable, the variable will be changed. If it is a single quotation mark, it is not so complex-directly display all strings contained in single quotation marks. Obviously, in PHP programming, it is faster to use single quotes to reference string variables than double quotes.
4. avoid joint application control in the database
Compared with other Web programming languages, PHP databases are very powerful. However, the running of databases in PHP is still a very time-consuming and laborious task. Therefore, as a Web programmer, we should minimize the control of database queries, at the same time, appropriate indexes should be created for the database. Another thing worth noting is that when using PHP to control the database, try not to apply the joint control of multiple data tables as much as possible. Although the joint control can enhance the database query efficiency, but it greatly increases the server burden.
To clarify the title, let's take a look at the simple example below.
We created two data tables foo and big_foo in the database. In the data table foo, there is only one field that contains all the natural numbers from 1. The data table big_foo also has only one field, but contains all the natural numbers from 1 to 1,000,000. Therefore, in terms of size, big_foo is the joint control between foo and itself.
$ Db-> query ('select * from Foo ');
Secs 0.032273
$ Db-> next_record ();
Secs 0.00048999999999999
$ Db-> query ('Insert into foo values (NULL )');
Secs 0.019506
$ Db-> query ('select * from foo as a, foo as B ');
Secs 17.280596
$ Db-> query ('select * from foo as a, foo as B where a. id> B. id ');
Secs 14.645251
$ Db-> query ('select * from foo as a, foo as B where a. id = B. id ');
Secs 0.041269
$ Db-> query ('select * from big_foo ');
Secs 25.393672
From the above control results we can find that the speed of joining two data tables with 1000 records is not much faster than that of a large data table with 1000000 records.
5. pay attention to the difference between include and require.
In PHP, the include () and require () functions are the same, but there are some differences in usage. include () is a conditional function, while require () it is an unconditional include function. For example, in the following example, if the variable $ somgthing is true, it will contain the file somefile:
If ($ something ){
Include ('somefile ');
}
However, no matter what value $ something takes, the following code will include the file somefile into the file:
If ($ something ){
Require ('somefile ');
}
The interesting example below demonstrates the differences between the two functions.
$ I = 1;
While ($ I <3 ){
Require ('somefile. $ I ');
$ I ++;
}
In this code, each loop contains the same file. Obviously, this is not the programmer's original intention. we can see from the code that this code looks forward to including different files in each loop. To accomplish this, you must turn to the include () function ():
$ I = 1;
While ($ I <3 ){
Include ('somefile. $ I ');
$ I ++;
}
6. pay attention to the differences between echo and print.
The echo and print functions in PHP are also similar, but there are also slight differences between the two. In PHP code, print can be used as a common function. for example, after the code below is executed, the value of the variable $ res will be 1.
$ Ret = print 'Hello World ';
This means that print is available in some complex expressions, but echo is not. Similarly, the echo statement runs slightly faster than the print statement in the code, because the echo statement does not request to return any value.