How to Become a PHP master? Learn to "lazy" programming

Source: Internet
Author: User
Tags contains explode include mysql in php and php code php programming reference
PHP is an efficient network programming language, because it has the advantages of flexible writing, fast running and so on, quickly become the preferred language of web programmers. A recent authoritative survey showed that 31.6% of websites now use PHP as the primary server-side programming language.

But it's not easy to be a master of PHP programming. Not as many people imagine, as long as you can quickly write a few simple code to solve a complex problem is the Master of PHP programming, the real PHP master will need to consider more other issues. The following three guidelines are guidelines that a mature PHP programmer should follow first in programming.

1. Laziness is gold

2. Write Beautiful Code

3. Pursue the speed of the program, not the speed of programming

   One, laziness is gold

Do you want to be a lazy programmer? That's a strange idea! Because the busiest person in the world is probably a computer programmer. But it's because programmers are so busy that they should learn to slack off when they're programmed.

For a programmer, there are two ways to be lazy: first, boldly use someone else's program code, and incorporate that code into your own program or project. The second is to write some useful code to build a function library, in the future to write programs can be conveniently picked, save a lot of duplication of labor, natural can be lazy a little.
Both of these lazy methods are perfect for PHP programmers.

First, PHP is a language of birth and growth in a free and open environment. Around the world, there are tens of thousands of programmers who have been struggling 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 PHP websites, mailing lists and newsgroups every day. In this way, I am not encouraging you to wait for others to write code for you, but you can "stand on the shoulders of great men", fully develop "copycat", smart application of other people'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 a few general functions, some of which come from some open source projects on the Internet, some are selected from the mailing list. 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 powerful database processing capability. However, in PHP, some specific functions are used for different databases, and there is a lack of common database processing functions. This greatly reduces the program code portability, which also for beginners programming friends brought a lot of inconvenience.

On the web, many programmers solve this problem by encapsulating classes. They write unified functions to handle any popular database, whether it's a popular MySQL in the Linux World or a popular SQL Server on a Windows platform. Personally, I like to use these functions, because you can directly use some simple functions such as "Query", "Next_record", and do not need to consider the database connection, database handle these complex things, and do not need to consider what kind of database.

If you need these functions, you can access 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 to Perl that can be in Linux or DOS environment directly run. In fact, we can complete the debugging of PHP by using the Echo statement flexibly.

The following functions allow you to view 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 (the 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 (the 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 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 to control log information

Another important way to debug a PHP program is to view log information. If you can easily control the log information level and log information display content, will bring more convenience to the program debugging. The following functions can be easily implemented with 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 if the log level is below 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, debug-level information is ignored. In addition, we can also set the display of the information content, 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 the log information at any time:

Ss_log_reset ();

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 that is 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 it's easy to check the execution time of any piece of code, even if we can use multiple timers at the same time, just use a few of these functions to set different parameters as the name of the timer.

5. Debugging and optimizing the operation of the database

For a database, running speed is critical. Although many books and articles teach a quick way to run a database, all methods have to be tested in practice. Here we will combine the query () function in the Phplib function library with the functions described above, and write the new query () function, which increases the monitoring function of running time compared to the previous 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;
}

   second, the preparation of beautiful code

1. Separate the background program from the front-end program

When writing a PHP program, some of the code is used to handle transactions, such as manipulating the database, doing math, and so on, while some other code is just the result of the transaction processing, For example, some PHP code that uses the Echo statement to display results in HTML format in a Web browser, and HTML code that embeds PHP programs directly. First, we should clearly distinguish between the two code, the former called the background program, the latter 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 provides a lot of convenience for programming. However, "extremes", if in a longer program in the PHP code and HTML code mixed writing, which will make the program messy, not conducive to the maintenance and reading of the program. So we need to transplant as much of the PHP code in the HTML code as possible into these programs, encapsulate the code into functions in a specialized file, and then use the INCLUDE statement in the HTML code to include the files and call them in the right place.

This approach makes both HTML code and PHP code easy to read, and because the HTML code needs to be constantly updated, this decoupled method ensures that the daemon is not corrupted.

Unlike the front-end program, the background program is more stable, structured, rarely changed, so it should be carefully designed and managed. In fact, in the design of the program, put a lot of time is worthwhile, "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 Include files

As mentioned earlier, background programs should be arranged in a series of include files. Include files can be loaded dynamically when needed through include statements, or they can be preloaded automatically in php.ini files by using the Auto_prepend_file directive.

If the latter method is used, the benefits will be once and for all, but there are some drawbacks that deserve our attention. The following code shows us how long it takes to parse a large included 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 containing file, the results show that parsing the containing file took 0.6 seconds, for a large web site, this speed is not negligible.

Another disadvantage of using include files is that if one of the statements in a file is wrong, the entire Web site's PHP program will not run. So use it and be careful.

In fact, a little processing of the containing file allows the inclusion file to be parsed only when needed. The following code makes the Abc.inc file parse 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, object-oriented programming methods are excellent programmers highly respected a software design method, in the PHP programming can give full play to the advantages of object-oriented language, programming objects in the encapsulation. In the previous code, we used an object-oriented approach, for example, when managing a database, we encapsulated the query () function into a database class, which greatly facilitated the management of the code and increased the readability of the program.

   third, the pursuit of the speed of the program, not the speed of programming

In the construction of the website, the program running speed andWeb pageDownload speed is an important factor in the success of the relationship. As a web programmer, you should pay more attention to how fast your code is running. Several of the methods described below increase the speed of your code to varying degrees.

1. Use embedded HTML code, not PHP's echo statement.

Because PHP is an embedded web programming language, you can embed HTML code and PHP code into each other. But many programmers are concerned about the excessive use of "" embedded PHP code in the HTML code will invoke the PHP interpreter multiple times, thus reducing the speed of PHP code, so prefer to use the PHP echo statement to output HTML code, rather than directly using HTML code. But the exact opposite is true. Each PHP page only calls once PHP interpreter to explain all the PHP code, so, only when needed to embed PHP code, and most of the time directly using the HTML code input results, not only will not reduce the speed of the program, but also because of the reduction of the Echo statement parsing, You can often improve the speed of your code.

The following piece of code proves our conclusion. In this code, we use the time test function described earlier.

Use Str-replace instead of Ereg-replace

Programmers who are accustomed to programming with Perl are more willing to use ereg_replace to complete string substitution, because ereg_replace usage in PHP is similar to that of pattern matching in Perl. However, the following code demonstrates that using Str_replace instead of ereg_replace can greatly improve the speed of your code.

Test Str_replace and ereg_replace running speed

This code tests how fast Str_replace is running

Emphasis? >

For ($i =0 $i <1000; $i + +) {
Str_replace (i>, b>, $string). ;
}
? >

This code tests how fast Ereg_replace is running

For ($i =0 $i <1000; $i + +) {
Ereg_replace (< ([/]*) i>, <\1b>, $string).
;
}
? >

//PrintResults
Conclusion

Time to use Str_replace-
Time to use Ereg_pattern-
Run the above code and get the result:

Time to use Str_replace-0.089757
Time to use Ereg_pattern-0.248881

From the results of the run we can see that using str_replace instead of ereg_replace as a string substitution function greatly improves the speed of the code.

3. Note the reference to the string

PHP, like many other programming languages, can use double quotes ("") to refer to strings, or to use single quotes (). But in PHP, if you use double quotes to refer to a string, the PHP parser will first parse the string for a reference to a variable, and then replace the variable with a variable. If it's a single quote, it's not so complicated--directly displays all the strings that are enclosed in single quotes. Obviously, in PHP programming, using single quotes to refer to string variables is quicker than using double quotes.

4. Avoid using federated operations in the database

PHP's database functions are powerful compared to other Web programming languages. But in PHP, the database operation is still a very time-consuming and laborious thing, so as a web programmer, to minimize the database query operations, but also to establish an appropriate index for the database. Another noteworthy thing is that when using PHP to manipulate a database, it is possible to not use a joint operation with multiple tables, although joint operations can enhance the query function of the database, but greatly increase the burden on the server.

To illustrate this, let's take a look at this simple example below.

We created two datasheet foo and Big_foo in the database. In Datasheet foo, there is only one field that contains all the natural numbers from 1-1000. The datasheet 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, we can see that for two data tables with 1000 records, the speed is no faster than the single operation of a large data table with 1 million records.

5. Note the difference between include and require

In PHP, include () and require () have the same functionality, but there are some differences in usage, include () is a conditional inclusion function, and 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 value the $something takes, the following code will include the file Somefile in the file:

if ($something) {
Require ("Somefile");
}
The following interesting example fully 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 the code wants 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. Note the difference between Echo and print

The functions of ECHO and print are basically the same in PHP, but there is a slight difference between the two. You can use print as a normal function in your 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, while Echo is not. Similarly, the Echo statement runs slightly faster in code than the print statement, because the Echo statement does not require any numeric values to be returned.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.