Home Backend Development PHP Tutorial How to become a PHP master_PHP tutorial

How to become a PHP master_PHP tutorial

Jul 20, 2016 am 11:17 AM
php how it fast become yes flexible of write programming language network run master Efficient

PHP is an efficient network programming language. Due to its advantages of flexible writing and fast running, PHP has quickly become the preferred language for Web programmers. So how can you become a good PHP developer?

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 is still a master. There are many other issues to consider. 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

Be a lazy programmer? This idea is so weird! Because the busiest people in the world may be 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 methods:

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 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.

In this way, 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", fully develop the "use doctrine", and intelligently apply other people's program codes to 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.

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 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.

Personally, the author likes 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. 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.")";  }  }

  需要的时候,在程序中简单地加入下面的一条代码即可查看程序中的所使用的变量(包括数组和对象)的类型和值:

  echo ss_as_string($my_variable);

  使用下面的语句,我们可以直接查看程序中所有的变量的值:

  echo ss_as_string($GLOBALS);

  3. 控制Log信息的函数

  调试PHP  程序的另外一种重要的方法就是查看Log信息。如果能够方便地控制Log信息的级别以及Log信息的显示内容,将会给程序调试带来更多的便利。下面的几个函数可以方便地实现这个功能。

  $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]) { // 不显示Log信息 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); }

  在上面的函数中,有四个Log级别变量。运行PHP程序时,只有当Log的级别低于预设的级别值时,Log信息才可以被记录和显示出来。例如,在程序中加入如下的一条语句:

  ss_log_set_level(INFO);

  那么,运行PHP程序时,只有ERROR和INFO级别的LOG信息才能被记录和显示出来,DEBUG级的信息则被忽略了。除此之外,我们还可以设定显示的信息内容,其语句如下:

  ss_log(ERROR, "testing level ERROR");

  ss_log(INFO, "testing level INFO");

  ss_log(DEBUG, "testing level DEBUG");

  你也可以随时使用下面的语句清空LOG信息:

  4.速度测试函数

  为了优化代码,我们需要一种可以测试代码运行时间的方法,从而来选择最优的代码。下面的函数可以测试运行代码所需的时间:

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

  现在可以轻松地检查任何一段代码的执行时间了,甚至我们可以同时使用多个计时器,只需在使用上述的几个函数时设定不同的参数作为计时器的名称就可以了。

  5.调试和优化数据库的操作

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 huge 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, 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.

 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 following code 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 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 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371996.htmlTechArticlePHP is an efficient network programming language. Due to its advantages of flexible writing and fast operation, it has quickly become the Web The language of choice for programmers. So how can you become an excellent PHP developer...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles