Table of Contents
2. Do not use require, include, include_once, required_once directly
3. Reserve debugging code for the application
4. Use cross-platform functions to execute commands
5. Flexible writing of functions
7. Collect all input somewhere and output it to the browser at once
8. Send the correct mime type header information, if the output For non-html content.
10. Use htmlentities to set the correct encoding options
Home Backend Development PHP Tutorial Ways to improve PHP code quality

Ways to improve PHP code quality

Mar 08, 2018 pm 02:27 PM
php method quality

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');
Copy after login

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
Copy after login

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
Copy after login

Now, no matter which directory you move to, such as moving to an external server, the code will run correctly without any changes.

2. Do not use require, include, include_once, required_once directly

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');
Copy after login

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');
Copy after login

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 );
    }
}
Copy after login

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.

3. Reserve debugging code for the application

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";
    }
}
Copy after login

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";
    }
}
Copy after login

4. Use cross-platform functions to execute commands

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');
Copy after login

The above function will run the shell command as long as there is a system function available, which maintains Code consistency.

5. Flexible writing of functions

function add_to_cart($item_id , $qty){
    $_SESSION['cart']['item_id'] = $qty;
}

add_to_cart( 'IPHONE3' , 2 );
Copy after login

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) );
Copy after login

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
Copy after login

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
Copy after login

index.php

require_once(&#39;super_class.php&#39;);//echo an image or pdf , or set the cookies or session data
Copy after login

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
Copy after login

This will be better.

7. Collect all input somewhere and output it to the browser at once

This is called output buffering. If you have output content in different functions:

function print_header(){    echo "<p id=&#39;header&#39;>Site Log and Login links</p>";
}function print_footer(){    echo "<p id=&#39;footer&#39;>Site was made by me</p>";
}

print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
print_footer();
Copy after login

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=&#39;header&#39;>Site Log and Login links</p>";    return $o;
}function print_footer(){
    $o = "<p id=&#39;footer&#39;>Site was made by me</p>";    return $o;
}echo print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
echo print_footer();
Copy after login

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.

8. Send the correct mime type header information, if the output For non-html content.

Output some xml.

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataecho $xml;
Copy after login

Works well. But needs some improvement.

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataheader("content-type: text/xml");echo $xml;
Copy after login

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";
Copy after login

CSS

header("content-type: text/css");echo "#p id { background:#000; }";
Copy after login

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 , &#39;UTF8&#39; ))
{	die(&#39;mysqli_set_charset() failed&#39;);
}
Copy after login

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.

10. Use htmlentities to set the correct encoding options

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);
Copy after login

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!

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
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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

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

See all articles