PHP is an efficient network programming language, because it has the advantages of flexible writing, fast running, and quickly become the preferred language for Web programmers. So how do you become a good PHP developer?
To become a PHP programmer is not easy, not as many people think, as long as you can quickly write a few simple code to solve a complex problem is the PHP programmer, the real PHP master also need to consider more other issues. The following three guidelines are guidelines that a mature PHP programmer should follow first in programming.
Laziness is gold.
Write nice code.
Pursue the speed of the program, not the speed of programming
Laziness is gold.
Be a lazy programmer? That's a strange idea! Because the busiest person in the world may be a computer programmer. But it is because programmers are too busy to learn to be lazy when programming. For a programmer, there are two ways to be lazy:
One is to use the code of someone else's program and put it into your own program or project. The other is to write some useful code to build a library of functions, in the future to write programs can be easily picked up, save a lot of repetitive work, nature can be lazy a little. Both of these lazy methods are ideal for PHP programmers.
First, PHP is a language that has been born and raised in a free and open environment. Around the world, there are thousands of programmers who are constantly striving for the perfection of PHP and are willing to share their ingenuity and code with others. You can find a lot of good program code from some PHP websites, mailing lists and newsgroups every day.
In this way, I'm not encouraging you to wait all day for someone to write code for you, but you can "stand on the shoulders of great men" and fully develop "take doctrine", and intelligently apply someone else's program code can save you a lot of time. Second, in PHP, you can easily build your own library of functions, which can save you a lot of trouble when you write your program later.
The following author introduces several common functions, some of which come from some open source projects on the Web, and some are featured from mailing lists. If you can add them to your own library of functions, sooner or later you will find yourself benefiting.
1. Common Database processing functions
One of the advantages of PHP compared to other CGI functions is that it has a very powerful database processing capability. However, in PHP, there are specific functions for different databases that are used specifically for processing, and the lack of a common database processing function. This greatly reduces the portability of the program code, which also brings a lot of inconvenience to the novice programming friends.
On the web, many programmers solve this problem through encapsulation classes. They have written a unified function to handle any popular database-whether it's a popular MySQL in Linux world or a widely popular SQL Server on the Windows platform.
Personally, I like the use of these functions, because you can directly use some simple such as "query", "Next_record" and other functions, without having to consider the database connection, database handle these complex things, but also do not need to consider what kind of database to use. If you need these functions, you can get them by visiting several of the following URLs:
http://phplib.netuse.de/
Http://phpclasses.UpperDesign.com/browse.html/package/20
http://phpdb.linuxbox.com/
2. Variable Debug function
PHP program debugging has always been a headache, it is not like VB and other high-level languages such as the integration of the compilation debugging environment, and do not want Perl as can be in the Linux or DOS environment directly run. In fact, we have the flexibility to use the Echo statement to complete the debugging work of PHP. The following functions allow you to view the type and value of any variable in your program at any time.
Function ss_array_as_string (& $array, $column = 0) {$str = "array (n"; while (List ($var, $val) = All ($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 ";" and "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, $col UMN); } 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 see 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 view the values of all variables in the program directly:
echo ss_as_string ($GLOBALS);
3. Functions that control log information
Another important way to debug a PHP program is to look at the log information. If it is convenient to control the level of log information and the display of log information, it will bring more convenience to the debugging of the program. Here are a few functions that can be conveniently implemented in 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 message 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 if the log level is lower than the preset level value. For example, add one of the following statements to your program:
Ss_log_set_level (INFO);
Then, when running the PHP program, only the error and info level log information can be recorded and displayed, the debug level of information is ignored. In addition, we can also set the display of the information content, 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 empty the log information at any time:
4. Speed Test function
To optimize the code, we need a way to test the running time of the code to select the best code. The following function can test the time it takes 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; }
It is now easy to check the execution time of any piece of code, even if we can use multiple timers at the same time, simply by setting different parameters as the name of the timer when using several of the above functions.
5. Debugging and optimizing the operation of the database
For a database, the speed of operation is critical. Although many books and articles teach some quick ways to run a database, all methods must be tested in practice. Below we will combine the query () function in the Phplib library with the several functions described above to write the new query () function, which increases the monitoring function of elapsed time compared to the original 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 nice code.
1. Separate the daemon from the front-end program
When writing a PHP program, some code is used to handle some transactions, such as manipulating databases, doing mathematical operations, and some other code is just the result of transaction processing, For example, some of the PHP code that uses the Echo statement to display the results in HTML format on a Web browser and those that embed directly into a PHP program. First of all, we should clearly distinguish between these two code, the former is called the background program, the latter is called the front-end program.
Because PHP is an embedded programming language, that is, all of the PHP code can be embedded in the HTML code, which brings a lot of convenience to the program writing. However, "extremes meet", if the PHP code and HTML code mixed in a longer program, this will make the program disorganized, not conducive to the maintenance and reading of the program.
So we need to try to transplant the PHP code in these programs into the HTML code as much as possible, encapsulate the code into functions in a specialized file, and then use the INCLUDE statement in the HTML code to include the files and invoke them in the appropriate place.
This approach makes both the HTML code and the PHP code easy to read and, on the other hand, because the HTML code needs to be constantly updated, and this separate method ensures that the daemon is not corrupted. Unlike the front-end program, the background program is more stable, structured, rarely changed, so should be carefully designed and managed. In fact, in the design of the program, invest a lot of time is worth, "now trees, after the cool", in the future design work will be able to easily use the background program now written.
2. Flexible use of included files
As mentioned earlier, background programs should be arranged in a series of include files. The include file can be loaded dynamically as needed by the include statement, or it can be pre-loaded automatically in the php.ini file by using the Auto_prepend_file directive. If we use the latter method, although the benefits have been achieved once and for all, but there are some shortcomings worthy of our attention. The following piece of code shows us how long it takes to parse a large containing 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 containing file, the result of the run shows that parsing the containing file took 0.6 seconds, for a large website, this speed is not negligible. Another disadvantage of using include files is that if one statement in a file has an error, the entire Web site's PHP program will not work. So use it and be careful. In fact, the inclusion file is slightly processed, which means that the containing 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. Using object-oriented programming methods
PHP is also an object-oriented language, the object-oriented programming method is a very good programmer of a software design method, in PHP programming can give full play to the advantages of object-oriented language, programming objects in the encapsulation. In the preceding code, we used an object-oriented approach, such as when we managed the database, we encapsulated the query () function into the database class, which greatly facilitated the management of the code and increased the readability of the program.
Pursuit of program speed, not programming speed
In the website construction, the program running speed and the webpage download speed are all the important factors of the relationship success or failure. As a web programmer, you should pay more attention to how fast your code is running. Several of the methods described below have increased the speed of code to varying degrees.
1. Use the embedded HTML code instead of the Echo statement in PHP.
Because PHP is an embedded web programming language, you can embed HTML code and PHP code with each other. But many programmers worry that too much of the "" embedded PHP code in the HTML code will invoke the PHP interpreter multiple times, thereby reducing the speed of PHP code, preferring to use the Echo statement of PHP to output HTML code instead of using HTML code directly.
But the exact opposite is true. Each PHP page only calls the PHP interpreter to explain all the PHP code, so, only when needed to embed the PHP code, and most of the time the direct use of HTML code input results, not only will not reduce the speed of the program, but also because of the reduction of ECHO statement parsing, It is often possible to increase the speed of code running. The following piece of code proves our conclusion. In this code, we use the time test function described earlier.
2. Use Str-replace instead of Ereg-replace
Programmers who are accustomed to programming with Perl are more likely to use ereg_replace to do string substitution work, because the use of ereg_replace in PHP is similar to that of pattern matching in Perl. However, the following code proves that using Str_replace instead of ereg_replace can greatly improve the speed of your code. Test the operating speed of the Str_replace and ereg_replace:
This code tests the Str_replace run speed emphasis;?>
for ($i =0; $i <1000; $i + +) {
Str_replace (I>, B>, $string).
;
}
This code tests the speed at which the ereg_replace runs
for ($i =0; $i <1000; $i + +) {
Ereg_replace (< ([/]*) i>, <1b>, $string).
;
}
3. Note the reference to the string
PHP, like many other programming languages, can use double quotation marks ("") to refer to a string, or you can use single quotation marks (). In PHP, however, if you use double quotation marks to refer to a string, the PHP parser will first parse the string with a reference to the variable and replace it with a variable. If it's a single quote, it's not so complicated--just display all the strings that enclose the single quotation marks directly. Obviously, in PHP programming, it is quicker to use single quotation marks to refer to string variables than to use double quotes.
4. Avoid the use of federated operations in the database
PHP has a very powerful database function compared to other Web programming languages. However, in PHP the operation of the database is still a very time-consuming task, so, as a web programmer, to minimize the database query operations, and should establish a proper index for the database.
Another notable thing is that when working with a database in PHP, it is possible not to use multiple data tables for federated operations, although federated operations can enhance the query functionality of the database, but it greatly increases the burden on the server. To illustrate this problem, we can look at this 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-1000. The data table Big_foo also has only one field, but contains all the natural numbers from 1-1 to 000,000. So, in terms of size, Big_foo equals foo with its own joint operation.
$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 results we can find that two data tables with 1000 records are combined at a speed that is no faster than a single 1 million-record large data table.
5. Note the difference between include and require
In PHP, the Include () function is the same as require (), but there are some differences in usage, include () is conditional include function, and 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, regardless of the $something value, the following code will include the file somefile into the file:
if ($something) {
Require ("Somefile");
}
The following interesting example illustrates the difference between the two functions.
$i = 1;
while ($i < 3) {
Require ("Somefile. $i");
$i + +;
}
In this code, every time a loop is made, the program will include the same file. Obviously this is not the intention of the programmer, and from the code we can see that this code wants to include different files in each loop. If you want to complete this function, you must ask for the function include ();
$i = 1;
while ($i < 3) {
Include ("Somefile. $i");
$i + +;
}
6. Notice 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. In PHP code, print can be used as a normal function, 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, while 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 values to be returned.
http://www.bkjia.com/PHPjc/371996.html www.bkjia.com true http://www.bkjia.com/PHPjc/371996.html techarticle PHP is an efficient network programming language, because it has the advantages of flexible writing, fast running, and quickly become the preferred language for Web programmers. So how to become a good PHP open ...