As a PHP programmer, of course I hope that my PHP code will be of high quality. This article mainly shares with you methods to improve the quality of PHP code, hoping to help you.
1. Do not use relative paths
You often see:
require_once('../../lib/some_class.php');
This method has many shortcomings:
It first looks for the specified php include path, and then looks for the current directory.
Therefore, too many paths will be checked.
If the script is included by a script in another directory, its base directory becomes becomes the directory where another script is located.
Another problem is that when the scheduled task runs the script, its parent directory may not be the working directory.
So the best choice is to use absolute Path:
define('ROOT' , '/var/www/project/');require_once(ROOT . '../../lib/some_class.php');//rest of the code
We have defined an absolute path and the value is hard-coded. We can also improve it. The path /var/www/project may also change, so do we have to change it every time? No, we can use the __FILE__ constant, such as:
//suppose your script is /var/www/project/index.php//Then __FILE__ will always have that full path.define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));require_once(ROOT . '../../lib/some_class.php');//rest of the code
Now, no matter which directory you move to, such as moving to an external server, the code will run correctly without any changes.
You can introduce multiple files at the head of the script, such as class libraries, tool files and helper functions, such as:
require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php');
This usage is quite primitive. It should be more flexible. A helper function should be written to include the file. For example:
function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); require_once( $path ); } load_class('Database'); load_class('Mail');
What is the difference? This code is more readable.
will In the future, you can extend this function as needed, such as:
function load_class($class_name){ //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); } }
You can also do more:
Find multiple directories for the same file
You can easily change the placement The directory of class files does not need to be modified one by one everywhere in the code
You can use similar functions to load files, such as html content.
In the development environment, we print the database query, dump the problematic variable values, and once the problem is solved, we comment or delete them. However, a better approach is to keep the debug code.
In the development environment , you can:
define('ENVIRONMENT' , 'development');if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
In the server, you can:
define('ENVIRONMENT' , 'production');if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
system, exec, passthru, shell_exec these 4 There are several functions that can be used to execute system commands. The behavior of each is slightly different. The problem is that when in shared hosting, some functions may be selectively disabled. Most newbies tend to first check which function is available each time, however Use it again.
A better solution is to encapsulate the function into a cross-platform function.
/** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec */ function terminal($command) { //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var); } terminal('ls');
The above function will run the shell command as long as there is a system function available, which maintains Code consistency.
function add_to_cart($item_id , $qty){ $_SESSION['cart']['item_id'] = $qty; } add_to_cart( 'IPHONE3' , 2 );
Use the above function to add a single item. When adding a list of items, do you want to create another function? No, just If you pay a little attention to different types of parameters, you will be more flexible. For example:
function add_to_cart($item_id , $qty){ if(!is_array($item_id)) { $_SESSION['cart']['item_id'] = $qty; } else { foreach($item_id as $i_id => $qty) { $_SESSION['cart']['i_id'] = $qty; } } } add_to_cart( 'IPHONE3' , 2 ); add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );
Now, the same function can handle different types of input parameters. You can refer to the above example to refactor your code to make it more flexible. It's smarter.
6. Intentionally ignore php closing tags
I'd love to know why so many blog posts about php advice don't mention this.
<?phpecho "Hello";//Now dont close this tag
This will save you a lot of time. Let's take an example:
A super_class.php file
<?phpclass super_class{ function super_function() { //super code } }?>//super extra character after the closing tag
index.php
require_once('super_class.php');//echo an image or pdf , or set the cookies or session data
In this way, you will get a Headers already sent error. Why? Because "super extra character" has been output. Now you have to start debugging. This will take a lot of time to find the location of super extra.
Therefore, develop the habit of omitting the closing character:
<?phpclass super_class{ function super_function() { //super code } }//No closing tag
This will be better.
This is called output buffering. If you have output content in different functions:
function print_header(){ echo "<p id='header'>Site Log and Login links</p>"; }function print_footer(){ echo "<p id='footer'>Site was made by me</p>"; } print_header();for($i = 0 ; $i < 100; $i++) { echo "I is : $i <br />'; } print_footer();
Alternatively, collect the output centrally somewhere. You can store it in a local variable of the function, or you can use ob_start and ob_end_clean. As follows:
function print_header(){ $o = "<p id='header'>Site Log and Login links</p>"; return $o; }function print_footer(){ $o = "<p id='footer'>Site was made by me</p>"; return $o; }echo print_header();for($i = 0 ; $i < 100; $i++) { echo "I is : $i <br />'; } echo print_footer();
Why you need output buffering:
>> ;You can change the output before sending it to the browser. For example, the str_replaces function or maybe preg_replaces or add some monitoring/debugging html content.
>>It is very easy to output to the browser while doing PHP processing Oops. You should have seen error messages appearing in the sidebar or middle of some sites. Do you know why it happens? Because processing and output are mixed.
Output some xml.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>";//Send xml dataecho $xml;
Works well. But needs some improvement.
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>";//Send xml dataheader("content-type: text/xml");echo $xml;
Pay attention to the header line. This line tells the browser what is being sent xml type content. So the browser can process it correctly. Many javascript libraries also rely on header information.
Similarly include javascript, css, jpg image, png image:
JavaScript
header("content-type: application/x-javascript"); echo "var a = 10";
CSS
header("content-type: text/css");echo "#p id { background:#000; }";
I once encountered that unicode/utf-8 encoding was set in the mysql table, and phpadmin could display it correctly, but when you get the content and output it on the page, an error message will appear. Garbled characters. The problem here lies in the character encoding of the mysql connection.
//Attempt to connect to database$c = mysqli_connect($this->host , $this->username, $this->password);//Check connection validityif (!$c) { die ("Could not connect to the database host: <br />". mysqli_connect_error()); }//Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )) { die('mysqli_set_charset() failed'); }
Once connected to the database, it is best to set the characterset of the connection. If your application wants to support multiple languages, this is necessary.
Before php5.4, the default encoding of characters is ISO-8859-1, and cannot be directly output such as À â, etc.
$value = htmlentities($this->value , ENT_QUOTES , CHARSET);
php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.
The above is the detailed content of Ways to improve PHP code quality. For more information, please follow other related articles on the PHP Chinese website!