MENU service case
 Website construction website design Beijing website construction high-end website production company Shangpin China
We create by embracing change
360 ° brand value__
simplified Chinese character
Simplified Chinese English

Shangpin China Joins Hands with Beisheng Internet to Create a New Chapter in Website Construction

Type: Shangpin Dynamic Learn more

Teach you how to become a PHP expert

Source: Shangpin China | Type: website encyclopedia | Time: 2012-11-07

Teach you how to become a PHP expert

PHP is an efficient network programming language. Because it has the advantages of flexible writing and fast running, it quickly becomes the preferred language for Web programmers. So how can I become an excellent PHP developer?

It is not easy to become a PHP programmer. 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 programmer. A real PHP programmer needs to consider more other issues. The following three guidelines are the first guidelines that a mature PHP programmer should follow in programming. ( Beijing website production )

◆ Laziness is golden

◆ Write beautiful code

◆ Pursue the speed of program rather than the speed of programming

Laziness is gold

Be a lazy programmer? This idea is too strange! Because the busiest person in the world is probably a computer programmer. But because programmers are too busy, they should learn to be lazy when programming. For a programmer, there are two ways to be lazy:

First, boldly use the ready-made program code of others and incorporate it into your own program or project. The second is to write some useful code to build a function library, which can be easily picked up when writing programs in the future, saving a lot of repetitive work, and naturally you can be lazy. These two lazy methods are very suitable for PHP programmers.

First of all, PHP is a language born and growing in a free and open environment. There are thousands of programmers around the world who have been striving for the perfection of PHP, and they are willing to share their intelligence and code with others. You can find a lot of excellent 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 others to write code for you, but you can "stand on the shoulders of great people", fully carry forward the "take it" principle, and intelligently apply other people's code can save you a lot of 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.

Here are some general functions introduced by the author. Some of these functions come from open source projects on the Internet, and some are selected from mailing lists. If you can add them to your own function library, sooner or later you will find that you will benefit a lot.

1. General database processing function

Compared with other CGI functions, one of the advantages of PHP is its powerful database processing capability. However, in PHP, for different databases, some specific functions are used for special processing, 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 beginners.

On the Internet, many programmers have solved this problem by encapsulating classes. They have written unified functions to deal with any popular database - whether it is MySQL, which is popular in the Linux world, or SqlServer, which is widely popular on the Windows platform. ( High end website construction )

Personally, the author likes to use these functions, because some simple functions such as "query" and "next_record" can be used directly, without considering the database connection, database handle and other complex things, let alone the type of database used. If you need these functions, you can get them by visiting the following websites:

  ◆ //phplib.netuse.de/

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

  ◆ //phpdb.linuxbox.com/
2. Variable debugging function

Debugging PHP programs has always been a headache. It neither has an integrated compilation and debugging environment like VB and other high-level languages, nor can it run directly in Linux or DOS like Perl. In fact, we can debug PHP by flexibly using echo statements. The following functions allow you to view the type and value of any variable 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. for  ( $i  = 0;   $i  <  $column ;   $i ++){ 
  10.   $str  .=   "&nbsp;&nbsp;&nbsp;&nbsp;" ;  
  11. return   $str .);  
  12.  } 
  13.   function  ss_object_as_string (& $object $column  = 0) { 
  14. if  ( empty empty ( $object ->classname)) { 
  15.   return   "$object" ;  
  16. else  { 
  17.   $str  =  $object ->classname. "( n" ;  
  18. while  (list(, $var ) = each( $object ->persistent_slots)) { 
  19.   for  ( $i  = 0;   $i  <  $column ;   $i ++){ 
  20. $str  .=   "&nbsp;&nbsp;&nbsp;&nbsp;" ;  
  21.  } 
  22.   global  $ $var ;  
  23.   $str  .=   $var . ==> ;  
  24.   $str  .=  ss_as_string($ $var , column+1). " n" ;  
  25. for  ( $i  = 0;   $i  <  $column ;   $i ++){ 
  26.   $str  .=   "&nbsp;&nbsp;&nbsp;&nbsp;" ;  
  27. return   $str .);  
  28.  } 
  29.   function  ss_as_string (& $thing $column  = 0) { 
  30.   if  ( is_object ( $thing )) { 
  31. return  ss_object_as_string( $thing $column );  
  32.  } 
  33.   elseif  ( is_array ( $thing )) { 
  34. return  ss_array_as_string( $thing $column );  
  35.  } 
  36.   elseif  ( is_double ( $thing )) { 
  37. return   "Double(" . $thing . ")" ;  
  38.  } 
  39.   elseif  ( is_long ( $thing )) { 
  40. return   "Long(" . $thing . ")" ;  
  41.  } 
  42.   elseif  ( is_string ( $thing )) { 
  43. return   "String(" . $thing . ")" ;  
  44.  } 
  45.   else  { 
  46. return   "Unknown(" . $thing . ")" ;  
  47.  } 
  48.  } 

When necessary, 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 that control log information

Another important way to debug PHP programs is to view the 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.

  1. $ss_log_level  = 0;  
  2. $ss_log_filename  = /tmp/ss-log;  
  3. $ss_log_levels  =  array
  4.  NONE => 0, 
  5.  ERROR => 1, 
  6.  INFO => 2, 
  7.  DEBUG => 3);  
  8. function  ss_log_set_level ( $level  = ERROR) { 
  9.   global   $ss_log_level ;  
  10.   $ss_log_level  =  $level ;  
  11. function  ss_log ( $level $message ) { 
  12.   global   $ss_log_level $ss -log-filename;  
  13.   if  ( $ss_log_levels [ $ss_log_level ] <  $ss_log_levels [ $level ]) { 
  14. //Do not display log information  
  15. return  false;  
  16.  } 
  17.   $fd  =  fopen ( $ss_log_filename "a+" );  
  18.   fputs ( $fd $level . - [.ss_timestamp_pretty().] - . $message . "n" );  
  19.  fclose( $fd );  
  20.   return  true;  
  21. function  ss_log_reset () { 
  22.   global   $ss_log_filename ;  
  23.  @unlink( $ss_log_filename );  

In the above function, there are four Log level variables. When running PHP programs, 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 PHP programs, 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 LOG information at any time:
4. Speed test function

In order to optimize the code, we need a method that can test the running time of the code, so as to select the optimal 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. function  ss_timing_stop ( $name  =  default ) { 
  5.   global   $ss_timing_stop_times ;  
  6.   $ss_timing_stop_times [ $name ] =  explode (, microtime());  
  7. function  ss_timing_current ( $name  =  default ) { 
  8.   global   $ss_timing_start_times $ss_timing_stop_times ;  
  9.   if  (!isset( $ss_timing_start_times [ $name ])) { 
  10. return  0;  
  11.  } 
  12.   if  (!isset( $ss_timing_stop_times [ $name ])) { 
  13. $stop_time  =  explode (, microtime());  
  14.  } 
  15.   else  { 
  16. $stop_time  =  $ss_timing_stop_times [ $name ];  
  17.  } 
  18.   $current  =  $stop_time [1] -  $ss_timing_start_times [ $name ][1];  
  19.   $current  +=  $stop_time [0] -  $ss_timing_start_times [ $name ][0];  
  20.   return   $current ;  

Now it is easy to check the execution time of any piece of code, and even we can use multiple timers at the same time. Just set different parameters as the names of timers when using the above functions.
5. Debugging and optimizing database operations

For database, running speed is crucial. Although many books and articles have taught some methods to run the database quickly, all methods must be tested by practice. Next, we will combine the query() function in the PHPLib function library and several functions described above to write a new query() function. Compared with the original function, this function adds the runtime 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;  
1. Separate the background program from the front-end program

When writing PHP programs, some codes are used to deal with some transactions, such as operating databases and performing mathematical operations, while others are only used to display the results of transaction processing, such as some PHP codes that use echo statements to display the results in HTML format on the Web browser, and those HTML codes that are directly embedded in PHP programs. First of all, we should clearly distinguish these two kinds of codes, and call the former background program and the latter 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 many conveniences for programming. However, "things turn against each other when they reach the extreme". If PHP code and HTML code are mixed in a long program, it will make the program disorderly and not conducive to program maintenance and reading.

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

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 updated constantly, this separation method can ensure that the background program will not be damaged. Different from the front-end program, the back-end program is more stable and structured, with few changes, so it should be carefully designed and managed. In fact, it is worthwhile to invest a lot of time in designing the platform program. "Plant trees now and enjoy the cool in the future" will make it easy to use the background program written now in future design work.

2. Flexible use of included files

As mentioned earlier, the daemon should be arranged in a series of include files. The include file can be loaded dynamically when needed through the include statement, or automatically loaded in advance in the php.ini file by using the auto_prepend_file command. If the latter method is used, although the benefits are obtained once and for all, there are also some disadvantages worth our attention. The following code shows that parsing a large include file takes a certain amount of time:

  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 took 0.6 seconds to parse the 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 run. So it is very careful to use it. In fact, by slightly processing the include file, the include file can be parsed only when needed. The following code makes the abc.inc file 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 praised by excellent programmers. In PHP programming, the advantages of object-oriented language can be fully used to encapsulate the objects in programming. In the previous code, we used the object-oriented method. For example, when managing the database, we encapsulated the query() function into the database class, which greatly facilitated the code management and increased the readability of the program.

Pursue program speed, not programming speed

In website construction, both the running speed of the program and the download speed of the webpage are important factors for success or failure. As a Web programmer, you should pay more attention to the running speed of the code. The following methods have improved the running speed of the code to varying degrees.

   1. Use embedded HTML code instead of PHP echo statements.

Because PHP is an embedded Web programming language, you can embed HTML code and PHP code into each other. However, many programmers worry that too much use of "" embedded PHP code in HTML code will call the PHP interpreter many times, which will reduce the running speed of PHP code. Therefore, they prefer to use PHP echo statements to output HTML code instead of directly using HTML code.

But the opposite is true. Each PHP page only calls the PHP interpreter once to interpret all PHP code. Therefore, PHP code is embedded only when needed. Most of the time, using HTML code directly to input results will not reduce the running speed of the program, and because the parsing of echo statements is reduced, the running speed of the code can often be improved. The following code proves our conclusion. In this code, we use the time test function described earlier.

  2. Use str replace instead of ereg replace

Programmers accustomed to programming in Perl are more willing to use ereg_replace to complete string replacement, because the usage 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 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).

  ;

  }

3. Note the reference of string

PHP, like many other programming languages, can use double quotation marks ("") to reference strings, or single quotation marks (). However, in PHP, if double quotation marks are used to reference strings, the PHP parser will first analyze whether there are references to variables in the strings. If there are variables, they will be replaced. If it is a single quotation mark, it is not so complicated - all strings contained in the single quotation mark are displayed directly. Obviously, in PHP programming, using single quotation marks to reference string variables is faster than using double quotation marks.

4. Avoid using union operations in the database

Compared with other Web programming languages, PHP's database function is very powerful. However, the database operation in PHP is still a time-consuming and laborious thing. Therefore, as a Web programmer, you should try to reduce the query operation of the database, and at the same time, you should establish an appropriate index for the database.

Another thing worth noting is that when using PHP to operate the database, try not to use the joint operation of multiple data tables. Although the joint operation can enhance the query function of the database, it greatly increases the burden of the server. To illustrate this problem, we can take a look at the following simple example.

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-1000. The data table big_foo also has only one field, but contains all natural numbers from 1-1000000. Therefore, in terms of size, big_foo is equal to that foo and itself are jointly operated.

  $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 combining two data tables with 1000 records is not much faster than that of a single large data table with 1000000 records.

5. Note the difference between include and require

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

  if($something){

  include("somefile");

  }

Regardless of the value of $something, the following code will include the file somefile into 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, the program will include the same file every time it loops. Obviously, this is not the original intention of the programmer. From the code, we can see that this code hopes to include different files in each cycle. 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 in PHP are basically the same, but there are slight differences between them. In PHP code, print can be used as a common 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, but echo cannot. Similarly, the echo statement runs slightly faster than the print statement in code, because the echo statement does not require any value to be returned.

Source Statement: This article is original or edited by Shangpin China's editors. If it needs to be reproduced, please indicate that it is from Shangpin China. The above contents (including pictures and words) are from the Internet. If there is any infringement, please contact us in time (010-60259772).
TAG label:

What if your website can increase the number of conversions and improve customer satisfaction?

Make an appointment with a professional consultant to communicate!

* Shangpin professional consultant will contact you as soon as possible

Disclaimer

Thank you very much for visiting our website. Please read all the terms of this statement carefully before you use this website.

1. Part of the content of this site comes from the network, and the copyright of some articles and pictures involved belongs to the original author. The reprint of this site is for everyone to learn and exchange, and should not be used for any commercial activities.

2. This website does not assume any form of loss or injury caused by users to themselves and others due to the use of these resources.

3. For issues not covered in this statement, please refer to relevant national laws and regulations. In case of conflict between this statement and national laws and regulations, the national laws and regulations shall prevail.

4. If it infringes your legitimate rights and interests, please contact us in time, and we will delete the relevant content at the first time!

Contact: 010-60259772
E-mail: [email protected]

Communicate with professional consultants now!

  • National Service Hotline

    400-700-4979

  • Beijing Service Hotline

    010-60259772

Please be assured to fill in the information protection
Online consultation

Disclaimer

Thank you very much for visiting our website. Please read all the terms of this statement carefully before you use this website.

1. Part of the content of this site comes from the network, and the copyright of some articles and pictures involved belongs to the original author. The reprint of this site is for everyone to learn and exchange, and should not be used for any commercial activities.

2. This website does not assume any form of loss or injury caused by users to themselves and others due to the use of these resources.

3. For issues not covered in this statement, please refer to relevant national laws and regulations. In case of conflict between this statement and national laws and regulations, the national laws and regulations shall prevail.

4. If it infringes your legitimate rights and interests, please contact us in time, and we will delete the relevant content at the first time!

Contact: 010-60259772
E-mail: [email protected]