1. Do not use relative paths
For example
Require_once ('.. /.. /lib/some_class.php ');
There are many drawbacks to this approach:
1) It first finds the specified PHP include path and then finds the current directory
2) If the script is included in a script from another directory, its base directory becomes the directory where the other script resides
3) When a timed task runs the script, its parent directory may not be the working directory
So the correct wording is:
Define (' ROOT ', PathInfo (__file__, pathinfo_dirname)); Require_once (ROOT. ‘.. /.. /lib/some_class.php ');
2, do not directly use require, include, include_once, required_once
Require_once (' lib/database.php '); require_once (' lib/mail.php '); require_once (' helpers/utitlity_functions.php ');
This usage is quite primitive. should be more flexible. You should write an assistant function containing the file
function Load_class ($class _name) {$path = ROOT. '/lib/'. $class _name. '. php '); require_once ($path);} Load_class (' Database '); Load_class (' Mail ');
Is there anything different? The code is more readable, and you can extend the function as needed.
function Load_class ($class _name) {$path = ROOT. '/lib/'. $class _name. '. php '); if (file_exists ($path)) {include ($path);}}
You can also do more:
1) Find multiple directories for the same file
2) can easily change the directory of the placement of the class file, no need to change in the code one by one
3) You can use a similar function to load files, such as HTML content
However, it is strongly recommended to use include, require instead of include_once, require_once
3. Use cross-platform functions to execute commands
/** Method to execute a command in the terminal uses:1. System 2. PassThru 3. EXEC 4. Shell_exec */function terminal ($command) { if (function_exists (' system ')) {Ob_start (); System ($command, $return _ var); $output = Ob_get_contents (); Ob_end_clean (); } ElseIf (function_exists (' PassThru ')) {Ob_start (); PassThru ($command, $return _var); $output = Ob_get_contents (); Ob_end_clean (); } ElseIf (function_exists (' exec ')) {exec ($command, $output, $return _var), $output = implode ("\ n", $output);} ElseIf (function_exists (' shell_exec ')) {$output = Shell_exec ($command);} else {$output = ' command execution not possible On the system '; $return _var = 1; }return Array (' output ' = $output, ' status ' = $return _var); } terminal (' ls ');
4. Ignore PHP close tag
<?php class Super_class {function super_function () { }}//no closing tag
That would be better.
5. Collect all inputs in one place and output them to the browser one at a time
This is called output buffering, if you have output content in a different function:
function Print_header () {echo "<div id= ' header ' >site Log and Login links</div>";} function Print_footer () {echo "<div id= ' footer ' >site is made by me</div>";} Print_header (); for ($i = 0; $i < $i + +) {echo "I is: $i ';} Print_footer ();
Alternative, collect the output centrally in a place. You can store them in local variables of a function, or you can use Ob_start and Ob_end_clean. As follows:
function Print_header () {$o = "<div id= ' header ' >site Log and Login links</div>"; return $o;} function Print_footer () {$o = "<div id= ' footer ' >site is made by me</div>"; return $o;} Echo Print_header (); for ($i = 0; $i < $i + +) {echo "I is: $i ';} Echo Print_footer ();
Why output buffering is required:
1) You can change the output before sending it to the browser. such as the Str_replaces function or the HTML content that might be preg_replaces or add some monitoring/debugging
2) output to the browser while doing PHP processing is very bad
6. Set the correct character encoding for MySQL connection
Attempt to connect to database $c = Mysqli_connect ($this->host, $this->username, $this->password); Check connection Validity if (! $c) {die ("Could does connect to the database host:". Mysqli_connect_error ());} Set the character set of the Connectionif (!mysqli_set_charset ($c, ' UTF8 ')) {die (' Mysqli_set_charset () failed ');} Once the database is connected, it is best to set the characterset of the connection. If your app supports multiple languages, this is a must.
7, do not use gzip compression output in the application, let Apache handle
Have you considered using Ob_gzhandler? Don't do that. There is no point. PHP only applies to writing apps. Don't worry about server and browser data transfer optimization issues, using Apache's Mod_gzip/mod_deflate module to compress content
8, before writing files, check the directory Write permission
$contents = "all the content"; $dir = '/var/www/project '; $file _path = $dir. "/content.txt", if (is_writable ($dir)) {file_put_contents ($file _path, $contents);} Else{die ("Directory $dir is not writable, or does not exist. Please check ");
9. Define static variables for variables with the same value in the function
Delay for some timefunction delay () {$sync _delay = get_option (' Sync_delay '), echo "Delaying for $sync _delay seconds ..."; Sleep ($sync _delay); echo "Done";} Replace with static variable://delay for some timefunction Delay () {static $sync _delay = Null;if ($sync _delay = null) {$sync _delay = get_option ( ' Sync_delay ');} echo "Delaying for $sync _delay seconds ..."; Sleep ($sync _delay); echo "Done";}
10. Do not use $_session variables directly
$_session[' username ' = $username; $username = $_session[' username '];
This can cause some problems. If multiple apps are running in the same domain name, the session variables may conflict. Two different applications may use the same session key. For example, a front-end portal that uses the same domain name as a backend management system.
From now on, use the application-related key and a wrapper function: Define (' app_id ', ' abc_corp_ecommerce '); Function to get a session variablefunction Session_get ($key) {$k = app_id. ‘.‘ . $key, if (Isset ($_session[$k)) {return $_session[$k];} return false;} Function set the session variablefunction Session_set ($key, $value) {$k = app_id. ‘.‘ . $key; $_session[$k] = $value; return true;}
11, the practical wording
>> use echo instead of print>> to replace preg_replace with str_replace unless you absolutely need >> do not use short tag>> simple strings with single quotes instead of double quotes > >head redirect remember to use exit>> do not call the function in the loop >>isset format code that is faster than strlen >> as in the beginning >> do not delete loops or if-else parentheses > > Don't try to omit some syntax to shorten the code. Instead, make your logic short >> use a text editor that has a highlighted syntax display. Highlighting syntax can help you reduce errors >> use PHP filter >> validate data to enforce type checking >> using Profiler, such as xdebug>>, to use a single database connection from start to finish if needed >> Avoid writing SQL directly, abstract >> use base tag in head >> never set error_reporting to 0 eg:error_reporting (~e_warning & ~e_notice & Amp ~E_STRICT);
12. Use Array_map to quickly process arrays
$arr = Array_map (' Trim ', $arr);
This applies the call trim for each element of the $arr array. Another similar function is Array_walk. Check out the documentation to learn more tips
13. Avoid using global variables
>> use defines/constants>> to get values using functions >> use classes and access by $this
14, do not rely too much on set_time_limit
Note that any external execution, such as system calls, socket operations, database operations, etc., is not under the control of set_time_limits. Therefore, even if the database spends a lot of time querying, the script does not stop executing. Subject to availability
Reference Original address: http://www.binarytides.com/40-techniques-to-enhance-your-php-code-part-2/
Some tips for improving PHP coding