PHP is an efficient network programming language. It is a preferred language for web programmers because of its flexible programming and fast running. So how can we become a good PHP developer?
It is not easy to become a PHP programming expert, as many people think, as long as you can quickly write a few simple code to solve a complicated problem, that is, a PHP programming expert, real PHP experts also need to consider more other issues. The following three principles should be followed by a mature PHP programmer in programming.
◆ Laziness is gold
◆ Write beautiful code
◆ The pursuit of program speed, rather than programming speed
Laziness is gold
Be a lazy programmer? This is a strange idea! This is because the busiest person in the world may be a computer programmer. But it is because programmers are too busy that they should learn to be lazy during programming. For a programmer, there are two lazy methods:
First, use the code of someone else 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, so you can naturally be a little lazy. Both of these methods are very suitable for PHP programmers.
First of all, PHP is a language born and grown in a free and open environment. There are thousands of programmers around the world who are constantly striving for PHP perfection and are willing to share their talents and code with others. Every day, you can find a lot of excellent program code from some PHP websites, email lists, and newsgroups.
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 ", smart Application 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 when writing programs later.
Below I will introduce several common functions, some of which come from some open source projects on the Internet and some of which are selected from the mail list. If you can add them to your own function library, sooner or later you will find yourself benefiting.
1. Common Database processing functions
Compared with other CGI functions, one of the advantages of PHP is its powerful database processing capability. However, in PHP, some specific functions are used for different databases for special processing, and common database processing functions are missing. This greatly reduces the portability of program code, which also brings a lot of inconvenience to beginners.
On the Internet, many programmers solve this problem through encapsulation. They have compiled unified functions to deal with any popular databases-MySQL, which is popular in the Linux World, and sqlserver, which is widely used on Windows platforms.
I personally like to use these functions, because some simple functions such as "query" and "next_record" can be used directly without consideration.
Database Connection and database handle are complex things that do not need to be considered. If you need these functions, you can access the following urls:
Http://phplib.netuse.de/
◆ Http://phpclasses.UpperDesign.com/browse.html/package/20
Http://phpdb.linuxbox.com/
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, nor does it need to be able to run in Linux or DOS environment like Perl.
Run directly. In fact, we can use echo statements flexibly to debug PHP. The following functions allow you to view the types and values of any variables in the program at any time.
1. function ss_array_as_string (&$array, $column = 0) {
2. $str = "Array(n";
3. while(list($var, $val) = each($array)){
4. for ($i = 0; $i < $column+1; $i++){
5. $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";
6. }
7. $str .= $var. ==> ;
8. $str .= ss_as_string($val, $column+1)." n";
9. }
10. for ($i = 0; $i < $column; $i++){
11. $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";
12. }
13. return $str.);
14. }
15. function ss_object_as_string (&$object, $column = 0) {
16. if (emptyempty($object->classname)) {
17. return "$object";
18. }
19. else {
20. $str = $object->classname."( n";
21. while (list(,$var) = each($object->persistent_slots)) {
22. for ($i = 0; $i < $column; $i++){
23. $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";
24. }
25. global $$var;
26. $str .= $var. ==> ;
27. $str .= ss_as_string($$var, column+1)." n";
28. }
29. for ($i = 0; $i < $column; $i++){
30. $str .= "&nbsp;&nbsp;&nbsp;&nbsp;";
31. }
32. return $str.);
33. }
34. }
35. function ss_as_string (&$thing, $column = 0) {
36. if (is_object($thing)) {
37. return ss_object_as_string($thing, $column);
38. }
39. elseif (is_array($thing)) {
40. return ss_array_as_string($thing, $column);
41. }
42. elseif (is_double($thing)) {
43. return "Double(".$thing.")";
44. }
45. elseif (is_long($thing)) {
46. return "Long(".$thing.")";
47. }
48. elseif (is_string($thing)) {
49. return "String(".$thing.")";
50. }
51. else {
52. return "Unknown(".$thing.")";
53. }
54. }
When necessary, simply add the following code to the program to view the types and values of the variables used in the Program (including arrays and objects:
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 control 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 be easily implemented.
# 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 log information at the error and info level can be recorded and displayed, while debug-level information is ignored. 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:
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:
1. function ss_timing_start ($name = default) {
2. global $ss_timing_start_times;
3. $ss_timing_start_times[$name] = explode( , microtime());
4. }
5. function ss_timing_stop ($name = default) {
6. global $ss_timing_stop_times;
7. $ss_timing_stop_times[$name] = explode(, microtime());
8. }
9. function ss_timing_current ($name = default) {
10. global $ss_timing_start_times, $ss_timing_stop_times;
11. if (!isset($ss_timing_start_times[$name])) {
12. return 0;
13. }
14. if (!isset($ss_timing_stop_times[$name])) {
15. $stop_time = explode(, microtime());
16. }
17. else {
18. $stop_time = $ss_timing_stop_times[$name];
19. }
20. $current = $stop_time[1] - $ss_timing_start_times[$name][1];
21. $current += $stop_time[0] - $ss_timing_start_times[$name][0];
22. return $current;
23. }
Now we can easily check the execution time of any piece of code. We can even use multiple timers at the same time, you only need to set different parameters as the timer name when using the above functions.
5. debug and optimize database operations
For databases, the running speed is crucial. Although many books and articles teach you how to quickly run databases, all methods must be tested in practice. Below we
The query () function in the phplib function library is combined with the functions described above to compile a new query () function. Compared with the original function, this function increases the running time.
Monitoring function.
1. function query($Query_String, $halt_on_error = 1) {
2. $this->connect();
3. ss_timing_start();
4. $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);
5. ss_timing_stop();
6. ss_log(INFO, ss_timing_current(). Secs - .$Query_String);
7. $this->Row = 0;
8. $this->Errno = mysql_errno();
9. $this->Error = mysql_error();
10. if ($halt_on_error && !$this->Query_ID) {
11. $this->halt("Invalid SQL: ".$Query_String);
12. }
13. return $this->Query_ID;
14. }
Write beautiful code
1. Separate background programs from front-end programs
When writing a PHP program, some code is used to process some transactions, such as database operations and mathematical operations. Other code is only displayed as the result of transaction processing, such as some
Use the echo statement to display the results in HTML format in the PHP code on the web browser and the HTML code that is directly embedded into the PHP program. First, we should clearly distinguish the two generations
Code, the former is called a background program, and the latter is called a front-end 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 maintenance and reading.
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, use the include statement in the HTML code to include these files, and call these functions at the appropriate location.
On the one hand, this method makes HTML code and PHP code easy to read, and on the other hand, because HTML code needs to be constantly updated, and this separation method can ensure that the background program will not be destroyed.
Different from front-end programs, background programs are more stable, structured, and rarely changed. Therefore, they should be carefully designed and managed. In fact, it is worthwhile to invest a lot of time in designing a program.
", You can easily use the background programs you have compiled in future design work.
2. flexible use of include files
As mentioned above, background programs should be arranged in a series of include files. You can use the include statement to dynamically load the included files as needed, or in the PHP. ini file.
The auto_prepend_file command is used to pre-automatically mount the file. If the latter method is used, although the benefits have been achieved once and for all, there are also some shortcomings that deserve our attention. Lower
The code below shows that it takes some time to parse a large file that contains:
Require (timing. Inc );
Ss_timing_start ();
Include (test. Inc );
Ss_timing_stop ();
Echo
. Ss_timing_current ().
;
In the code above, test. Inc is a 1000-row file. The running result shows that it takes 0.6 seconds to parse the file. For a large website
Speed is not negligible. Another disadvantage of using include files is that if a statement in a file is incorrect, the PHP program of the entire website cannot run. Therefore
And be careful. In fact, 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. Use object-oriented programming methods
PHP is also an object-oriented language. The object-oriented programming method is a software design method highly praised by excellent programmers. in PHP programming, you can give full play to the advantages of the object-oriented language.
Encapsulation of programming objects. In the previous code, we used an object-oriented method. For example, when managing a database, we encapsulated the query () function into the database class, which greatly facilitated
Added code management and program readability.
Pursuing program speed rather than 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 methods described below increase the code running speed to varying degrees.
1. Use embedded HTML code instead of PHP echo statements.
Because PHP is an embedded WEB programming language, HTML code and PHP code can be embedded into each other. However, many programmers are worried about using "" embedding too much in HTML code.
PHP code calls the PHP interpreter multiple times to reduce the running speed of PHP code. Therefore, PHP echo statements are preferred to output HTML code instead of HTML code.
But the opposite is true. Every PHP page only calls the PHP interpreter once to explain all the PHP code. Therefore, the PHP code is embedded only when necessary, and most of the time directly
Using HTML code to input results not only reduces the running speed of the program, but also reduces the resolution of echo statements, which often improves the running speed of the Code. The code below demonstrates our conclusion
Theory. In this Code, we used the time test function described above.
2. Use str-replace instead of ereg-replace
Programmers who are familiar with Perl programming are more willing to use ereg_replace to complete string replacement, because the usage and
The usage of pattern matching in Perl is similar. However, the following code proves that str_replace is used instead.
Ereg_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 ).
;
}
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 characters
String, the PHP parser will first analyze whether there is any reference to the variable in the string. If there is a variable, it will replace the variable. If it is a single quotation mark, it is not so complicated-a place that directly contains single quotation marks
Strings are directly displayed. Obviously, using single quotes to reference string variables in PHP programming is faster than using double quotes.
4. Avoid joint operations in the database
Compared with other Web programming languages, PHP databases are very powerful. However, running a database in PHP is still a very time-consuming and laborious task. Therefore, as a web programmer, we should minimize the number 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 operate a database, try not to use the union operation of multiple data tables. Even though the union operation can enhance the database query function, but it greatly increases the burden on the server. To illustrate this problem, let's take a look at the simple example below.
Two data tables Foo and big_foo are created in the database. In the data table Foo, there is only one field that contains all the natural numbers from 1. 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 equal to foo and it performs joint operations.
.
$ 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 operation 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. Note 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 include function, while
Require () 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 following interesting example fully 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 original intention of the programmer. From the code, we can see that this code will include different files in each loop. To complete this function, you must turn to the include () function ();
$ I = 1;
While ($ I <3 ){
Include (\ "somefile. $ I \");
$ I ++;
}
6. Note the difference between ECHO and print.
The ECHO and print functions in PHP are basically the same, but there are also slight differences between the two. Print can be used as a common function in PHP Code. For example, after executing the following code, 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 require any value to be returned.