PHP is an efficient network programming language. Due to its advantages of flexible writing and fast running, it has quickly become the preferred language for Web programmers. An authoritative survey not long ago showed that 31.6% of websites now use PHP as the main server-side programming language.
However, it is not easy to become a PHP programming master. It is not as many people imagine, as long as you can quickly write a few simple codes to solve a complex problem, you are a PHP programming master. A real PHP master also needs to consider many other issues. The following three guidelines are the guidelines that a mature PHP programmer should first follow in programming.
1. Laziness is golden
2. Write beautiful code
3. Pursue the speed of programming, not the speed of programming
1. Laziness is golden
Are you a lazy programmer? This idea is so strange! Because probably the busiest people in the world are computer programmers. But it is precisely because programmers are too busy that they should learn to be lazy when programming.
For a programmer, there are two lazy ways: 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.
These two lazy 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 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. By saying this, I am not encouraging you to wait all day for others to write code for you, but you can "stand on the shoulders of great men" and fully promote the "use doctrine". Smart application of other people's program codes can save you a lot of money. time. Secondly, in PHP, you can easily build your own function library, which can save you a lot of trouble when writing programs in the future.
The author below introduces several common functions to you. 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 that it has very 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. Personally, I like to use these functions very much, because you 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, let alone Consider what database you are using.
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/
http://www.phpchina.com
2. Variable debugging function
Debugging of 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 have the ability to be used in PHP programs like Perl. Run directly under 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 (empty($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. Functions that 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, and 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");
You can also use the following statement to clear the LOG information at any time:
ss_log_reset();
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;
$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 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;
}
2. Write beautiful code
1. Separate the back-end program from the front-end program.
When writing a PHP program, some codes are used to process some transactions, such as operating databases, performing mathematical operations, etc., while other codes are only for transaction processing. The results are displayed, such as some PHP code that uses the echo statement to display the results in HTML format on the Web browser and those HTML codes that are directly embedded in the PHP program. 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. Therefore, 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 at the appropriate location. Just call these functions.
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. Flexible use of include files
As mentioned earlier, 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. .
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 method
PHP is also an object-oriented language. Object-oriented programming method is a software design method highly respected by excellent programmers. In PHP programming, the advantages of object-oriented language can be fully utilized. The advantage is to encapsulate objects in programming. 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.
3. Pursue program speed rather than programming speed.
In website construction, program running speed and web page download speed are important factors that determine 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 worry 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. Therefore, they would rather use PHP's echo statement to output HTML code instead of directly Use HTML code. But the truth is exactly the opposite. Each PHP page only calls the PHP interpreter once to interpret all PHP codes. Therefore, embedding PHP codes only when needed, and most of the time directly using HTML codes to input results, will not only not reduce the running speed of the program, but 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.
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 following code proves that using str_replace instead of ereg_replace will greatly improve the running 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).
}
?>
//Print result
conclusion
using str_replace time -
Time to use ereg_pattern -
running the above code, the result is:
time to use str_replace - 0.089757
Time to use ereg_pattern - 0.248881
From the running results, we can see that using str_replace instead of ereg_replace as the string replacement function greatly improves the running speed of the code.
3. Pay attention to string quotation.
PHP, like many other programming languages, can use double quotation marks ("") to quote strings, or single quotation marks (). 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 joint 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 to 1,000,000. So, in terms of size, big_foo is equal to foo combined with itself.
$db->query("select * from foo");
0.032273 seconds
$db->next_record();
0.00048999999999999 secs
$db->query("insert into foo values (NULL)");
0.019506 seconds
$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 seconds
$db->query("select * from foo as a, foo as b where a.id = b.id");
0.041269 seconds
$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 functions, but there are some differences in usage. include() is a conditional inclusion function, while require() is an unconditional one. Contains functions. 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 value $something takes, the following code will include the file somefile into the file:
if($something){
require("somefile");
}
The following interesting example 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 include() function:
$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 an ordinary 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 runs slightly faster than the print statement in the code because the echo statement does not require any value to be returned.