Home  >  Article  >  Backend Development  >  PHP programming guidelines that PHP programmers must follow_PHP Tutorial

PHP programming guidelines that PHP programmers must follow_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:12:43873browse

PHP programming guidelines that PHP programmers must follow

How to become an excellent PHP developer? This is definitely a question that every PHP novice is asking. In fact, it is not easy to become a PHP programming master. A real PHP master also needs to consider many other issues. So how can you become an excellent PHP developer faster? Follow the Green Tea editor to find out!

The following three guidelines are the guidelines that a mature PHP programmer should first follow in programming:

 ◆Laziness is golden

 ◆Write beautiful code

 ◆Pursue the speed of the program, not the speed of programming

Laziness is golden

For a programmer, there are two ways to be lazy:

First, boldly use other people’s ready-made program codes and integrate these codes into your own programs or projects. The second is to write some useful codes to build a function library, which can be easily used when writing programs in the future. This saves a lot of repetitive work and naturally makes you less lazy. Both of these lazy methods are very suitable for PHP programmers.

First of all, PHP is a language that was born and grew up in a free and open environment. There are thousands of programmers around the world who have been constantly striving for the perfection of PHP, and they are also willing to share their ingenuity and the code they write with others. You can find a lot of excellent program code every day from some PHP websites, mailing lists, and news groups.

Next, I will introduce you to several common functions. Some of these functions come from some open source projects on the Internet, and some are selected from the mailing list. If you can add them to your own library, sooner or later you will find yourself benefiting from them.

 1. General database processing functions

Compared with other CGI functions, one of the advantages of PHP is its powerful database processing capabilities. However, in PHP, some specific functions are used to handle different databases, and there is a lack of general database processing functions. This greatly reduces the portability of program code, which also brings a lot of inconvenience to beginner programming friends.

On the Internet, many programmers have solved this problem by encapsulating classes. They wrote unified functions to handle any popular database - whether it is Mysql, which is popular in the Linux world, or SqlServer, which is widely popular on Windows platforms.

Some excellent PHP developers like to use these functions very much, because they can directly use some simple functions such as "query" and "next_record" without having to consider complicated things such as database connections and database handles. There is no need to consider which database is used. If you need these functions, you can get them by visiting the following URLs:

 ◆http://phplib.netuse.de/

 ◆http://phpclasses.UpperDesign.com/browse.html/package/20

 ◆http://phpdb.linuxbox.com/

 2. Variable debugging function

Debugging PHP programs has always been a headache. It does not have an integrated compilation and debugging environment like high-level languages ​​such as VB, nor does it like Perl, which can run directly in a Linux or DOS environment. In fact, we can complete the debugging of PHP by flexibly using the echo statement. The following functions allow you to check the type and value of any variable 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 .= " "; } $str .= $var. ==> ; $str .= ss_as_string($val, $column+1)." n "; } for ($i = 0; $i < $column; $i++){ $str .= " "; } return $str.); } function ss_object_as_string (&$object, $column = 0) { if (emptyempty($object->classname)) { return "$object"; } else { $str = $object->classname."( n"; while (list(,$var) = each($object- >persistent_slots)) { ​for ($i = 0; $i < $column; $i++){ $str .= " "; } ​global $$var; ​$str .= $var. ==> ; ​$ str .= ss_as_string($$var, column+1)." n"; } for ($i = 0; $i < $column; $i++){ $str .= " "; } 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 needed, simply add the following code to the program to view the types and values ​​of the variables (including arrays and objects) used in the program:

echo ss_as_string($my_variable);

Using the following statement, we can directly view the values ​​of all variables in the program:

echo ss_as_string($GLOBALS);

 3. Function to control Log information

Another important way to debug PHP programs is to view Log information. If you can easily control the level of Log information and the display content of Log information, it will bring more convenience to program debugging. The following functions can easily implement this function.

 $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, 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);

Then, when running a PHP program, only ERROR and INFO level LOG information can be recorded and displayed, while DEBUG level information is ignored. In addition, we can also set the displayed information content with the following statements:

 ss_log(ERROR, "testing level ERROR");

 ss_log(INFO, "testing level INFO");

 ss_log(DEBUG, "testing level DEBUG");

 4. Speed ​​test function

In order to optimize the code, we need a method that can test the running time of the code to select the optimal 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; ] = 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 you can easily check the execution time of any piece of code. We can even use multiple timers at the same time. We just need to set different parameters as the name of the timer when using the above functions.

5. Debugging and optimizing database operations

For databases, running speed is crucial. Although many books and articles teach methods for running databases quickly, all methods must be tested in practice. Next, we will combine the query() function in the PHPLib function library and the functions introduced above to write a new query() function. Compared with the original function, this function adds a running time monitoring function.

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; }

Write beautiful code

 1. Separate background programs from front-end programs

When writing PHP programs, some codes are used to process some transactions, such as operating databases, performing mathematical operations, etc., while other codes are only used to display the results of transaction processing, such as some using the echo statement to display the results in HTML. format that displays PHP code on a web browser as well as those HTML codes that are embedded directly into PHP programs. First of all, we should clearly distinguish between these two types of code, calling the former a background program and the latter a front-end program.

Because PHP is an embedded programming language, that is to say, all PHP code can be embedded in HTML code, which brings many conveniences to program writing. However, if things go to extremes, they must be reversed. If you mix PHP code and HTML code in a long program, it will make the program messy and unfavorable for the maintenance and reading of the program.

So we need to transplant the PHP code mixed in the HTML code in these programs as much as possible, encapsulate these codes into functions in special files, and then use the include statement in the HTML code to include these files. Just call these functions at the appropriate location.

On the one hand, this approach makes both the HTML code and the PHP code simple and easy to read. On the other hand, because the HTML code needs to be constantly updated, this separation method can ensure that the background program will not be destroyed. Unlike front-end programs, back-end programs pursue stability, structure, and rarely change, so they should be carefully designed and managed. In fact, it is worthwhile to invest a lot of time when designing desktop programs. "Plant trees now and enjoy the shade later." You will be able to easily use the background programs you write now in future design work.

 2. Use included files flexibly

As mentioned before, background programs should be arranged in a series of include files. Included files can be dynamically loaded when needed through the include statement, or they can be automatically loaded in advance by using the auto_prepend_file directive in the php.ini file. If you use the latter method, although you will get the benefits of once and for all, there are also some shortcomings worthy of our attention.

The following piece of code shows us how long it takes to parse a large include 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-line include file. The running results show that it takes 0.6 seconds to parse this include file. For a large website, this speed is not negligible. of. Another disadvantage of using include files is that if an error occurs in a statement in a file, the PHP program of the entire website will not be able to run. So use it very carefully. In fact, with a little processing of the include file, the include file can be parsed only when needed.

The following code causes the abc.inc file to be parsed 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 respected by excellent programmers. In PHP programming, you can give full play to the advantages of object-oriented languages ​​and control the objects in programming. Encapsulate. In the previous code, we used an object-oriented method. For example, when managing the database, we encapsulated the query() function into the database class, which greatly facilitated code management and increased the readability of the program.

Pursuing program speed, not programming speed

In website construction, program running speed and web page download speed are important factors related to success or failure. As a web programmer, you should pay more attention to the running speed of your code. Several methods introduced below all improve the running speed of the code to varying degrees.

 1. Use embedded HTML code instead of PHP’s echo statement.

Because PHP is an embedded Web programming language, HTML code and PHP code can be embedded in each other. However, many programmers are worried that excessive use of "" to embed PHP code in HTML code will call the PHP interpreter multiple times, thereby reducing the running speed of PHP code, so they would rather use PHP's echo statement to output HTML code instead of directly Use HTML code.

But the fact is exactly the opposite. Each PHP page only calls the PHP interpreter once to interpret all PHP codes. Therefore, the PHP code is only embedded when needed, and most of the time, the HTML code is used directly to input the results. Not only will it not reduce the running speed of the program, but it will also Because the parsing of echo statements is reduced, the running speed of the code can often be improved. The following piece of code demonstrates our conclusion. In this code, we use the time test function introduced earlier.

 2. Use str-replace instead of ereg-replace

Programmers who are used to programming in Perl are more willing to use ereg_replace to complete string replacement work, because the usage of ereg_replace in PHP is similar to the usage of pattern matching in Perl. However, the code below proves that using str_replace instead of ereg_replace will greatly improve the speed of the code.

Test the running speed of str_replace and ereg_replace:

//This code tests the running speed of str_replace emphasis; ?>

 for ($i=0; $i<1000; $i++) {

str_replace(i>, b>, $string).

;

 }

//This code tests the running speed of ereg_replace

 for ($i=0; $i<1000; $i++) {

ereg_replace(<([/]*)i>, <\1b>, $string).

;

 }

3. Pay attention to string references

PHP, like many other programming languages, can use double quotes ("") to quote strings, or single quotes (). But in PHP, if you use double quotes to quote a string, the PHP parser will first analyze whether there is a reference to a variable in the string. If there is a variable, it will replace the variable. If it is single quotes, it is not so complicated - all strings enclosed in single quotes are directly displayed. Obviously, in PHP programming, it is faster to use single quotes to quote string variables than double quotes.

 4. Avoid using union operations in the database

Compared with other Web programming languages, PHP’s database function is very powerful. However, running the database in PHP is still a very time-consuming and labor-intensive matter. Therefore, as a Web programmer, you must minimize database query operations and establish appropriate indexes for the database.

Another thing worth noting is that when using PHP to operate a database, try not to use joint operations of multiple data tables. Although joint operations can enhance the query function of the database, it greatly increases the burden on the server. To illustrate this problem, we can 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, which contains all natural numbers from 1 to 1000. The data table big_foo also has only one field, but contains all natural numbers from 1-1,000,000. So, in terms of size, big_foo is equal to foo combined with itself.

 $db->query("select * from foo");

 0.032273 secs

 $db->next_record();

 0.00048999999999999 secs

 $db->query("insert into foo values ​​(NULL)");

 0.019506 secs

 $db->query("select * from foo as a, foo as b");

 17.280596 secs

 $db->query("select * from foo as a, foo as b where a.id > b.id");

 14.645251 secs

 $db->query("select * from foo as a, foo as b where a.id = b.id");

 0.041269 secs

 $db->query("select * from big_foo");

 25.393672 secs

From the above operation results, we can find that the speed of joining two data tables with 1,000 records is not much faster than the separate operation of a large data table with 1,000,000 records.

5. Pay attention to the difference between include and require

In PHP programming, include() and require() have the same function, but there are some differences in usage. include() is a conditional inclusion function, while require() is an unconditional inclusion function. For example, in the following example, if the variable $somgthing is true, the file somefile will be included:

 if($something){

include("somefile");

 }

But no matter what the value of $something is, the following code will include the file somefile into the file:

 if($something){

require("somefile");

 }

The following interesting example fully illustrates the difference between these two functions.

 $i = 1;

while ($i < 3) {

require("somefile.$i");

$i++;

 }

In this code, the program will include the same file every time it loops. Obviously this is not the programmer's original intention. From the code we can see that this code hopes to include different files in each loop. If you want to complete this function, you must turn to the function include();

 $i = 1;

while ($i < 3) {

include("somefile.$i");

$i++;

 }

6. Pay attention to the difference between echo and print

The functions of echo and print in PHP are basically the same, but there are subtle differences between the two. You can use print as a normal 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 can be used in some complex expressions, but echo cannot. Similarly, the echo statement in the code runs slightly faster than the print statement because the echo statement does not require any value to be returned.

The above is an analysis of the three principles to become an excellent PHP developer. The editor of Green Tea would like to tell friends who have just started learning PHP: Everything is difficult at the beginning, but as long as you put in the effort, you will be rewarded.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/919975.htmlTechArticleThe PHP programming guidelines that PHP programmers must follow. How to become an excellent PHP developer? This must be every A question asked by every PHP newbie. In fact, you need to become a PHP programming master and...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn