Home >Backend Development >PHP Tutorial >36 Tips to Improve PHP Code Quality_PHP Tutorial

36 Tips to Improve PHP Code Quality_PHP Tutorial

WBOY
WBOYOriginal
2016-07-20 10:58:11864browse

1. Do not use relative paths

You often see:

<ol class="dp-c"><li class="alt"><span><span class="keyword">require_once</span><span>(</span><span class="string">'../../lib/some_class.php'</span><span>); </span></span></li></ol>

This method has many shortcomings:

It first looks for the specified php include path, and then looks for the current directory.

So too many paths are checked.

If the script is included by a script in another directory, its base directory becomes The directory where another script is located.

Another problem is that when a scheduled task runs the script, its parent directory may not be the working directory.

So the best choice is to use an absolute path :

<ol class="dp-c">
<li class="alt"><span><span>define(</span><span class="string">'ROOT'</span><span> , </span><span class="string">'/var/www/project/'</span><span>);  </span></span></li>
<li>
<span class="keyword">require_once</span><span>(ROOT . </span><span class="string">'../../lib/some_class.php'</span><span>);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//rest of the code</span><span> </span>
</li>
</ol>

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:

<ol class="dp-c">
<li class="alt"><span><span class="comment">//suppose your script is /var/www/project/index.php </span><span> </span></span></li>
<li>
<span class="comment">//Then __FILE__ will always have that full path. </span><span> </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>define(</span><span class="string">'ROOT'</span><span> , </span><span class="func">pathinfo</span><span>(</span><span class="keyword">__FILE__</span><span>, PATHINFO_DIRNAME));  </span>
</li>
<li class="alt">
<span class="keyword">require_once</span><span>(ROOT . </span><span class="string">'../../lib/some_class.php'</span><span>);  </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="comment">//rest of the code</span><span> </span>
</li>
</ol>

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, etc. , such as:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">require_once</span><span>(</span><span class="string">'lib/Database.php'</span><span>);  </span></span></li>
<li>
<span class="keyword">require_once</span><span>(</span><span class="string">'lib/Mail.php'</span><span>);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="keyword">require_once</span><span>(</span><span class="string">'helpers/utitlity_functions.php'</span><span>); </span>
</li>
</ol>

This usage is quite primitive. It should be more flexible. A helper function inclusion file should be written. For example:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> load_class(</span><span class="vars">$class_name</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//path to the class file </span><span> </span>
</li>
<li>
<span>    </span><span class="vars">$path</span><span> = ROOT . </span><span class="string">'/lib/'</span><span> . </span><span class="vars">$class_name</span><span> . </span><span class="string">'.php'</span><span>);  </span>
</li>
<li class="alt">
<span>    </span><span class="keyword">require_once</span><span>( </span><span class="vars">$path</span><span> );  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>load_class(</span><span class="string">'Database'</span><span>);  </span>
</li>
<li class="alt">
<span>load_class(</span><span class="string">'Mail'</span><span>); </span>
</li>
</ol>

Is there any difference? This code More readable.

You can extend this function as needed in the future, such as:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> load_class(</span><span class="vars">$class_name</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//path to the class file </span><span> </span>
</li>
<li>
<span>    </span><span class="vars">$path</span><span> = ROOT . </span><span class="string">'/lib/'</span><span> . </span><span class="vars">$class_name</span><span> . </span><span class="string">'.php'</span><span>);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">if</span><span>(</span><span class="func">file_exists</span><span>(</span><span class="vars">$path</span><span>))  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li>
<span>        </span><span class="keyword">require_once</span><span>( </span><span class="vars">$path</span><span> );  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span>} </span></li>
</ol>

You can also do more:

Find for the same file Multiple directories

can easily change the directory where class files are placed. There is no need to modify the code one by one.

You can use similar functions to load files, such as html content.

3. Keep debugging code for the application

In the development environment, we print the database query statements, dump the problematic variable values, and once the problem is solved, we comment or delete them However, a better approach is to keep the debugging code.

In a development environment, you can:

<ol class="dp-c">
<li class="alt"><span><span>define(</span><span class="string">'ENVIRONMENT'</span><span> , </span><span class="string">'development'</span><span>);  </span></span></li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">if</span><span>(! </span><span class="vars">$db</span><span>->query( </span><span class="vars">$query</span><span> )  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">if</span><span>(ENVIRONMENT == </span><span class="string">'development'</span><span>)  </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="func">echo</span><span> </span><span class="string">"$query failed"</span><span>;  </span>
</li>
<li><span>    }  </span></li>
<li class="alt">
<span>    </span><span class="keyword">else</span><span> </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="func">echo</span><span> </span><span class="string">"Database error. Please contact administrator"</span><span>;  </span>
</li>
<li><span>    }  </span></li>
<li class="alt"><span>} </span></li>
</ol>

In a server, you can:

<ol class="dp-c">
<li class="alt"><span><span>define(</span><span class="string">'ENVIRONMENT'</span><span> , </span><span class="string">'production'</span><span>);  </span></span></li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">if</span><span>(! </span><span class="vars">$db</span><span>->query( </span><span class="vars">$query</span><span> )  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">if</span><span>(ENVIRONMENT == </span><span class="string">'development'</span><span>)  </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="func">echo</span><span> </span><span class="string">"$query failed"</span><span>;  </span>
</li>
<li><span>    }  </span></li>
<li class="alt">
<span>    </span><span class="keyword">else</span><span> </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="func">echo</span><span> </span><span class="string">"Database error. Please contact administrator"</span><span>;  </span>
</li>
<li><span>    }  </span></li>
<li class="alt"><span>} </span></li>
</ol>

4. Use cross-platform functions to execute commands

The four functions system, exec, passthru, and shell_exec can be used to execute system commands. The behavior of each is slightly different. The problem is , when in shared hosting, certain functions may be selectively disabled. Most newbies tend to first check which function is available each time before using it.

A better solution is to enclose a function Cross-platform functions.

<ol class="dp-c">
<li class="alt"><span><span class="comment">/** </span> </span></li>
<li><span><span class="comment">    Method to execute a command in the terminal </span> </span></li>
<li class="alt"><span><span class="comment">    Uses : </span> </span></li>
<li><span> </span></li>
<li class="alt"><span><span class="comment">    1. system </span> </span></li>
<li><span><span class="comment">    2. passthru </span> </span></li>
<li class="alt"><span><span class="comment">    3. exec </span> </span></li>
<li><span><span class="comment">    4. shell_exec </span> </span></li>
<li class="alt"><span> </span></li>
<li><span><span class="comment">*/</span><span> </span></span></li>
<li class="alt">
<span class="keyword">function</span><span> terminal(</span><span class="vars">$command</span><span>)  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//system </span><span> </span>
</li>
<li>
<span>    </span><span class="keyword">if</span><span>(function_exists(</span><span class="string">'system'</span><span>))  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li><span>        ob_start();  </span></li>
<li class="alt">
<span>        system(</span><span class="vars">$command</span><span> , </span><span class="vars">$return_var</span><span>);  </span>
</li>
<li>
<span>        </span><span class="vars">$output</span><span> = ob_get_contents();  </span>
</li>
<li class="alt"><span>        ob_end_clean();  </span></li>
<li><span>    }  </span></li>
<li class="alt">
<span>    </span><span class="comment">//passthru </span><span> </span>
</li>
<li>
<span>    </span><span class="keyword">else</span><span> </span><span class="keyword">if</span><span>(function_exists(</span><span class="string">'passthru'</span><span>))  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li><span>        ob_start();  </span></li>
<li class="alt">
<span>        </span><span class="func">passthru</span><span>(</span><span class="vars">$command</span><span> , </span><span class="vars">$return_var</span><span>);  </span>
</li>
<li>
<span>        </span><span class="vars">$output</span><span> = ob_get_contents();  </span>
</li>
<li class="alt"><span>        ob_end_clean();  </span></li>
<li><span>    }  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="comment">//exec </span><span> </span>
</li>
<li class="alt">
<span>    </span><span class="keyword">else</span><span> </span><span class="keyword">if</span><span>(function_exists(</span><span class="string">'exec'</span><span>))  </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="func">exec</span><span>(</span><span class="vars">$command</span><span> , </span><span class="vars">$output</span><span> , </span><span class="vars">$return_var</span><span>);  </span>
</li>
<li>
<span>        </span><span class="vars">$output</span><span> = implode(</span><span class="string">"n"</span><span> , </span><span class="vars">$output</span><span>);  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="comment">//shell_exec </span><span> </span>
</li>
<li>
<span>    </span><span class="keyword">else</span><span> </span><span class="keyword">if</span><span>(function_exists(</span><span class="string">'shell_exec'</span><span>))  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li>
<span>        </span><span class="vars">$output</span><span> = shell_exec(</span><span class="vars">$command</span><span>) ;  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="keyword">else</span><span> </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="vars">$output</span><span> = </span><span class="string">'Command execution not possible on this system'</span><span>;  </span>
</li>
<li>
<span>        </span><span class="vars">$return_var</span><span> = 1;  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="keyword">return</span><span> </span><span class="keyword">array</span><span>(</span><span class="string">'output'</span><span> => </span><span class="vars">$output</span><span> , </span><span class="string">'status'</span><span> => </span><span class="vars">$return_var</span><span>);  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>terminal(</span><span class="string">'ls'</span><span>); </span>
</li>
</ol>

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

5. Flexible Write the function

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> add_to_cart(</span><span class="vars">$item_id</span><span> , </span><span class="vars">$qty</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$_SESSION</span><span>[</span><span class="string">'cart'</span><span>][</span><span class="string">'item_id'</span><span>] = </span><span class="vars">$qty</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>add_to_cart( </span><span class="string">'IPHONE3'</span><span> , 2 ); </span>
</li>
</ol>

to add a single item using the function above. And when adding a list of items, do you want to create another function? No, just pay attention to the different types of parameters. It will be more flexible. For example:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> add_to_cart(</span><span class="vars">$item_id</span><span> , </span><span class="vars">$qty</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">if</span><span>(!</span><span class="func">is_array</span><span>(</span><span class="vars">$item_id</span><span>))  </span>
</li>
<li><span>    {  </span></li>
<li class="alt">
<span>        </span><span class="vars">$_SESSION</span><span>[</span><span class="string">'cart'</span><span>][</span><span class="string">'item_id'</span><span>] = </span><span class="vars">$qty</span><span>;  </span>
</li>
<li><span>    }  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">else</span><span> </span>
</li>
<li class="alt"><span>    {  </span></li>
<li>
<span>        </span><span class="keyword">foreach</span><span>(</span><span class="vars">$item_id</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$i_id</span><span> => </span><span class="vars">$qty</span><span>)  </span>
</li>
<li class="alt"><span>        {  </span></li>
<li>
<span>            </span><span class="vars">$_SESSION</span><span>[</span><span class="string">'cart'</span><span>][</span><span class="string">'i_id'</span><span>] = </span><span class="vars">$qty</span><span>;  </span>
</li>
<li class="alt"><span>        }  </span></li>
<li><span>    }  </span></li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt">
<span>add_to_cart( </span><span class="string">'IPHONE3'</span><span> , 2 );  </span>
</li>
<li>
<span>add_to_cart( </span><span class="keyword">array</span><span>(</span><span class="string">'IPHONE3'</span><span> => 2 , </span><span class="string">'IPAD'</span><span> => 5) ); </span>
</li>
</ol>

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

6. Intentionally ignore php closing tags

I wonder why so many blog posts about php advice fail to mention this.

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></li><li><span> </span></li><li class="alt"><span class="func">echo</span><span> </span><span class="string">"Hello"</span><span>;  </span></li><li><span> </span></li><li class="alt"><span class="comment">//Now dont close this tag</span><span> </span></li></ol>

This will save you a lot of time. Let’s give an example:

a super_class.php file

<ol class="dp-c"><li class="alt"><span><span><?php  </span></span></li><li><span class="keyword">class</span><span> super_class  </span></li><li class="alt"><span>{  </span></li><li><span>    </span><span class="keyword">function</span><span> super_function()  </span></li><li class="alt"><span>    {  </span></li><li><span>        </span><span class="comment">//super code </span><span> </span></li><li class="alt"><span>    }  </span></li><li><span>}  </span></li><li class="alt"><span>?>  </span></span></li>
<li>
<span class="comment">//super extra character after the closing tag</span><span> </span>
</li>
</ol>

index.php

<ol class="dp-c">
<li class="alt"><span><span class="keyword">require_once</span><span>(</span><span class="string">'super_class.php'</span><span>);  </span></span></li>
<li><span> </span></li>
<li class="alt">
<span class="comment">//echo an image or pdf , or set the cookies or session data</span><span> </span>
</li>
</ol>

In this way, you will Get a Headers already send error. Why? Because the “super extra character” has already been output. Now you have to start debugging. This will take a lot of time to find the location of the super extra.

Therefore, make a habit of omitting shutdown Typical habits:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></li><li><span class="keyword">class</span><span> super_class  </span></li><li class="alt"><span>{  </span></li><li><span>    </span><span class="keyword">function</span><span> super_function()  </span></li><li class="alt"><span>    {  </span></li><li><span>        </span><span class="comment">//super code </span><span> </span></li><li class="alt"><span>    }  </span></li><li><span>}  </span></li><li class="alt"><span> </span></li><li><span class="comment">//No closing tag</span><span> </span></li></ol>

This would be better.

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

This is called output buffering, and let's say you have output in different functions:

<ol class="dp-c"><li class="alt"><span><span class="keyword">function</span><span> print_header()  </span></span></li><li><span>{  </span></li><li class="alt"><span>    </span><span class="func">echo</span><span> </span><span class="string">"<div id='header'>Site Log and Login links</div>"</span><span>;  </span></span></li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="keyword">function</span><span> print_footer()  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span>    </span><span class="func">echo</span><span> </span><span class="string">"<div id='footer'>Site was made by me</div>"</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt"><span>print_header();  </span></li>
<li>
<span class="keyword">for</span><span>(</span><span class="vars">$i</span><span> = 0 ; </span><span class="vars">$i</span><span> < 100; </span><span class="vars">$i</span><span>++)  </span></li><li class="alt"><span>{  </span></li><li><span>    </span><span class="func">echo</span><span> "I is : </span><span class="vars">$i</span><span> <br />';  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span>print_footer(); </span></li>
</ol>
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:
<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> print_header()  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$o</span><span> = </span><span class="string">"<div id='header'>Site Log and Login links</div>"</span><span>;  </span>
</li>
<li>
<span>    </span><span class="keyword">return</span><span> </span><span class="vars">$o</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">function</span><span> print_footer()  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$o</span><span> = </span><span class="string">"<div id='footer'>Site was made by me</div>"</span><span>;  </span>
</li>
<li>
<span>    </span><span class="keyword">return</span><span> </span><span class="vars">$o</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="func">echo</span><span> print_header();  </span>
</li>
<li>
<span class="keyword">for</span><span>(</span><span class="vars">$i</span><span> = 0 ; </span><span class="vars">$i</span><span> < 100; </span><span class="vars">$i</span><span>++)  </span></li><li class="alt"><span>{  </span></li><li><span>    </span><span class="func">echo</span><span> "I is : </span><span class="vars">$i</span><span> <br />';  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="func">echo</span><span> print_footer(); </span>
</li>
</ol>

Why output buffering is needed:

>>You can change the output before sending it to the browser. Such as str_replaces function or maybe preg_replaces or add some monitoring/debugging html content.

>>It is very bad to process the output to the browser while doing PHP processing. You should have seen error messages appearing in the sidebar or middle of some sites. Do you know why it happens? Because the processing and The output is mixed.

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

Output some xml.

<ol class="dp-c">
<li class="alt"><span><span class="vars">$xml</span><span> = </span><span class="string">'<?xml version="1.0" encoding="utf-8" standalone="yes"?>'</span><span>;  </span></span></li>
<li>
<span class="vars">$xml</span><span> = "<response>  </span>
</li>
<li class="alt"><span>  <code>0</code>  </span></li>
<li><span></response>";  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Send xml data </span><span> </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="vars">$xml</span><span>; </span>
</li>
</ol>

Works well. But needs some improvement.

<ol class="dp-c">
<li class="alt"><span><span class="vars">$xml</span><span> = </span><span class="string">'<?xml version="1.0" encoding="utf-8" standalone="yes"?>'</span><span>;  </span></span></li>
<li>
<span class="vars">$xml</span><span> = "<response>  </span>
</li>
<li class="alt"><span>  <code>0</code>  </span></li>
<li><span></response>";  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Send xml data </span><span> </span>
</li>
<li class="alt">
<span>header(</span><span class="string">"content-type: text/xml"</span><span>);  </span>
</li>
<li>
<span class="func">echo</span><span> </span><span class="vars">$xml</span><span>; </span>
</li>
</ol>

Pay attention to the header line. This line tells the browser that the content sent is xml type. So the browser can process it correctly. Many javascript libraries also Depends on header information.

Similar ones include javascript, css, jpg image, png image:

JavaScript

<ol class="dp-c">
<li class="alt"><span><span>header(</span><span class="string">"content-type: application/x-javascript"</span><span>);  </span></span></li>
<li>
<span class="func">echo</span><span> </span><span class="string">"var a = 10"</span><span>; </span>
</li>
</ol>

CSS

<ol class="dp-c">
<li class="alt"><span><span>header(</span><span class="string">"content-type: text/css"</span><span>);  </span></span></li>
<li>
<span class="func">echo</span><span> </span><span class="string">"#div id { background:#000; }"</span><span>; </span>
</li>
</ol>

9. Set the correct character encoding for mysql connection

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 When the page is output, garbled characters will appear. The problem here lies in the character encoding of the mysql connection.

<ol class="dp-c">
<li class="alt"><span><span class="comment">//Attempt to connect to database </span><span> </span></span></li>
<li>
<span class="vars">$c</span><span> = mysqli_connect(</span><span class="vars">$this</span><span>->host , </span><span class="vars">$this</span><span>->username, </span><span class="vars">$this</span><span>->password);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Check connection validity </span><span> </span>
</li>
<li class="alt">
<span class="keyword">if</span><span> (!</span><span class="vars">$c</span><span>)   </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">die</span><span> (</span><span class="string">"Could not connect to the database host: <br />"</span><span>. mysqli_connect_error());  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Set the character set of the connection </span><span> </span>
</li>
<li class="alt">
<span class="keyword">if</span><span>(!mysqli_set_charset ( </span><span class="vars">$c</span><span> , </span><span class="string">'UTF8'</span><span> ))  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">die</span><span>(</span><span class="string">'mysqli_set_charset() failed'</span><span>);  </span>
</li>
<li><span>} </span></li>
</ol>

Once you connect 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

php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如À â等.

<ol class="dp-c"><li class="alt"><span><span class="vars">$value</span><span> = htmlentities(</span><span class="vars">$this</span><span>->value , ENT_QUOTES , CHARSET); </span></span></li></ol>

php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.

11. 不要在应用中使用gzip压缩输出, 让apache处理

考虑过使用 ob_gzhandler 吗? 不要那样做. 毫无意义. php只应用来编写应用. 不应操心服务器和浏览器的数据传输优化问题.

使用apache的mod_gzip/mod_deflate 模块压缩内容.

12. 使用json_encode输出动态javascript内容

时常会用php输出动态javascript内容:

<ol class="dp-c">
<li class="alt"><span><span class="vars">$images</span><span> = </span><span class="keyword">array</span><span>(  </span></span></li>
<li>
<span> </span><span class="string">'myself.png'</span><span> , </span><span class="string">'friends.png'</span><span> , </span><span class="string">'colleagues.png'</span><span> </span>
</li>
<li class="alt"><span>);  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="vars">$js_code</span><span> = </span><span class="string">''</span><span>;  </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">foreach</span><span>(</span><span class="vars">$images</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$image</span><span>)  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span class="vars">$js_code</span><span> .= </span><span class="string">"'$image' ,"</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="vars">$js_code</span><span> = </span><span class="string">'var images = ['</span><span> . </span><span class="vars">$js_code</span><span> . </span><span class="string">']; '</span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="func">echo</span><span> </span><span class="vars">$js_code</span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];</span><span> </span>
</li>
</ol>

更聪明的做法, 使用 json_encode:

<ol class="dp-c">
<li class="alt"><span><span class="vars">$images</span><span> = </span><span class="keyword">array</span><span>(  </span></span></li>
<li>
<span> </span><span class="string">'myself.png'</span><span> , </span><span class="string">'friends.png'</span><span> , </span><span class="string">'colleagues.png'</span><span> </span>
</li>
<li class="alt"><span>);  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="vars">$js_code</span><span> = </span><span class="string">'var images = '</span><span> . json_encode(</span><span class="vars">$images</span><span>);  </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="vars">$js_code</span><span>;  </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="comment">//Output is : var images = ["myself.png","friends.png","colleagues.png"]</span><span> </span>
</li>
</ol>

优雅乎?

13. 写文件前, 检查目录写权限

写或保存文件前, 确保目录是可写的, 假如不可写, 输出错误信息. 这会节约你很多调试时间. linux系统中, 需要处理权限, 目录权限不当会导致很多很多的问题, 文件也有可能无法读取等等.

确保你的应用足够智能, 输出某些重要信息.

<ol class="dp-c">
<li class="alt"><span><span class="vars">$contents</span><span> = </span><span class="string">"All the content"</span><span>;  </span></span></li>
<li>
<span class="vars">$file_path</span><span> = </span><span class="string">"/var/www/project/content.txt"</span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="func">file_put_contents</span><span>(</span><span class="vars">$file_path</span><span> , </span><span class="vars">$contents</span><span>); </span>
</li>
</ol>

这大体上正确. 但有些间接的问题. file_put_contents 可能会由于几个原因失败:

>>父目录不存在

>>目录存在, 但不可写

>>文件被写锁住?

所以写文件前做明确的检查更好.

<ol class="dp-c">
<li class="alt"><span><span class="vars">$contents</span><span> = </span><span class="string">"All the content"</span><span>;  </span></span></li>
<li>
<span class="vars">$dir</span><span> = </span><span class="string">'/var/www/project'</span><span>;  </span>
</li>
<li class="alt">
<span class="vars">$file_path</span><span> = </span><span class="vars">$dir</span><span> . </span><span class="string">"/content.txt"</span><span>;  </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">if</span><span>(</span><span class="func">is_writable</span><span>(</span><span class="vars">$dir</span><span>))  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="func">file_put_contents</span><span>(</span><span class="vars">$file_path</span><span> , </span><span class="vars">$contents</span><span>);  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="keyword">else</span><span> </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">die</span><span>(</span><span class="string">"Directory $dir is not writable, or does not exist. Please check"</span><span>);  </span>
</li>
<li><span>} </span></li>
</ol>

这么做后, 你会得到一个文件在何处写及为什么失败的明确信息.

14. 更改应用创建的文件权限

在 linux环境中, 权限问题可能会浪费你很多时间. 从今往后, 无论何时, 当你创建一些文件后, 确保使用chmod设置正确权限. 否则的话, 可能文件先是由"php"用户创建, 但你用其它的用户登录工作, 系统將会拒绝访问或打开文件, 你不得不奋力获取root权限,  更改文件的权限等等.

<ol class="dp-c">
<li class="alt"><span><span class="comment">// Read and write for owner, read for everybody else </span><span> </span></span></li>
<li>
<span class="func">chmod</span><span>(</span><span class="string">"/somedir/somefile"</span><span>, 0644);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">// Everything for owner, read and execute for others </span><span> </span>
</li>
<li class="alt">
<span class="func">chmod</span><span>(</span><span class="string">"/somedir/somefile"</span><span>, 0755); </span>
</li>
</ol>

15. 不要依赖submit按钮值来检查表单提交行为

<ol class="dp-c">
<li class="alt"><span><span class="keyword">if</span><span>(</span><span class="vars">$_POST</span><span>[</span><span class="string">'submit'</span><span>] == </span><span class="string">'Save'</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//Save the things </span><span> </span>
</li>
<li><span>} </span></li>
</ol>

上面大多数情况正确, 除了应用是多语言的. 'Save' 可能代表其它含义. 你怎么区分它们呢. 因此, 不要依赖于submit按钮的值.

<ol class="dp-c">
<li class="alt"><span><span class="keyword">if</span><span>( </span><span class="vars">$_SERVER</span><span>[</span><span class="string">'REQUEST_METHOD'</span><span>] == </span><span class="string">'POST'</span><span> </span><span class="keyword">and</span><span> isset(</span><span class="vars">$_POST</span><span>[</span><span class="string">'submit'</span><span>]) )  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//Save the things </span><span> </span>
</li>
<li><span>} </span></li>
</ol>

现在你从submit按钮值中解脱出来了.

16. 为函数内总具有相同值的变量定义成静态变量

<ol class="dp-c">
<li class="alt"><span><span class="comment">//Delay for some time </span><span> </span></span></li>
<li>
<span class="keyword">function</span><span> delay()  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span>    </span><span class="vars">$sync_delay</span><span> = get_option(</span><span class="string">'sync_delay'</span><span>);  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="func">echo</span><span> </span><span class="string">"<br />Delaying for $sync_delay seconds..."</span><span>;  </span>
</li>
<li class="alt">
<span>    sleep(</span><span class="vars">$sync_delay</span><span>);  </span>
</li>
<li>
<span>    </span><span class="func">echo</span><span> </span><span class="string">"Done <br />"</span><span>;  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>

用静态变量取代:

<ol class="dp-c">
<li class="alt"><span><span class="comment">//Delay for some time </span><span> </span></span></li>
<li>
<span class="keyword">function</span><span> delay()  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span>    </span><span class="keyword">static</span><span> </span><span class="vars">$sync_delay</span><span> = null;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">if</span><span>(</span><span class="vars">$sync_delay</span><span> == null)  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li>
<span>    </span><span class="vars">$sync_delay</span><span> = get_option(</span><span class="string">'sync_delay'</span><span>);  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="func">echo</span><span> </span><span class="string">"<br />Delaying for $sync_delay seconds..."</span><span>;  </span>
</li>
<li>
<span>    sleep(</span><span class="vars">$sync_delay</span><span>);  </span>
</li>
<li class="alt">
<span>    </span><span class="func">echo</span><span> </span><span class="string">"Done <br />"</span><span>;  </span>
</li>
<li><span>} </span></li>
</ol>

17. 不要直接使用 $_SESSION 变量

<ol class="dp-c">
<li class="alt"><span><span class="vars">$_SESSION</span><span>[</span><span class="string">'username'</span><span>] = </span><span class="vars">$username</span><span>;  </span></span></li>
<li>
<span class="vars">$username</span><span> = </span><span class="vars">$_SESSION</span><span>[</span><span class="string">'username'</span><span>]; </span>
</li>
</ol>

这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个session key. 例如, 一个前端门户, 和一个后台管理系统使用同一域名.

从现在开始, 使用应用相关的key和一个包装函数:

<ol class="dp-c">
<li class="alt"><span><span>define(</span><span class="string">'APP_ID'</span><span> , </span><span class="string">'abc_corp_ecommerce'</span><span>);  </span></span></li>
<li><span> </span></li>
<li class="alt">
<span class="comment">//Function to get a session variable </span><span> </span>
</li>
<li>
<span class="keyword">function</span><span> session_get(</span><span class="vars">$key</span><span>)  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span>    </span><span class="vars">$k</span><span> = APP_ID . </span><span class="string">'.'</span><span> . </span><span class="vars">$key</span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">if</span><span>(isset(</span><span class="vars">$_SESSION</span><span>[</span><span class="vars">$k</span><span>]))  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li>
<span>        </span><span class="keyword">return</span><span> </span><span class="vars">$_SESSION</span><span>[</span><span class="vars">$k</span><span>];  </span>
</li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="keyword">return</span><span> false;  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="comment">//Function set the session variable </span><span> </span>
</li>
<li class="alt">
<span class="keyword">function</span><span> session_set(</span><span class="vars">$key</span><span> , </span><span class="vars">$value</span><span>)  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$k</span><span> = APP_ID . </span><span class="string">'.'</span><span> . </span><span class="vars">$key</span><span>;  </span>
</li>
<li>
<span>    </span><span class="vars">$_SESSION</span><span>[</span><span class="vars">$k</span><span>] = </span><span class="vars">$value</span><span>;  </span>
</li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">return</span><span> true;  </span>
</li>
<li class="alt"><span>} </span></li>
</ol>

18. 將工具函数封装到类中

假如你在某文件中定义了很多工具函数:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> utility_a()  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//This function does a utility thing like string processing </span><span> </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span> </span></li>
<li>
<span class="keyword">function</span><span> utility_b()  </span>
</li>
<li class="alt"><span>{  </span></li>
<li>
<span>    </span><span class="comment">//This function does nother utility thing like database processing </span><span> </span>
</li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="keyword">function</span><span> utility_c()  </span>
</li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="comment">//This function is ... </span><span> </span>
</li>
<li><span>} </span></li>
</ol>

这些函数的使用分散到应用各处. 你可能想將他们封装到某个类中:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">class</span><span> Utility  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="keyword">public</span><span> </span><span class="keyword">static</span><span> </span><span class="keyword">function</span><span> utility_a()  </span>
</li>
<li><span>    {  </span></li>
<li class="alt"><span> </span></li>
<li><span>    }  </span></li>
<li class="alt"><span> </span></li>
<li>
<span>    </span><span class="keyword">public</span><span> </span><span class="keyword">static</span><span> </span><span class="keyword">function</span><span> utility_b()  </span>
</li>
<li class="alt"><span>    {  </span></li>
<li><span> </span></li>
<li class="alt"><span>    }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>    </span><span class="keyword">public</span><span> </span><span class="keyword">static</span><span> </span><span class="keyword">function</span><span> utility_c()  </span>
</li>
<li><span>    {  </span></li>
<li class="alt"><span> </span></li>
<li><span>    }  </span></li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt">
<span class="comment">//and call them as  </span><span> </span>
</li>
<li><span> </span></li>
<li class="alt">
<span class="vars">$a</span><span> = Utility::utility_a();  </span>
</li>
<li>
<span class="vars">$b</span><span> = Utility::utility_b(); </span>
</li>
</ol>

显而易见的好处是, 如果php内建有同名的函数, 这样可以避免冲突.

另一种看法是, 你可以在同个应用中为同个类维护多个版本, 而不导致冲突. 这是封装的基本好处, 无它.

19. Bunch of silly tips 

>>使用echo取代print

>>使用str_replace取代preg_replace, 除非你绝对需要

>>不要使用 short tag

>>简单字符串用单引号取代双引号

>>head重定向后记得使用exit

>>不要在循环中调用函数

>>isset比strlen快

>>始中如一的格式化代码

>>不要删除循环或者if-else的括号

不要这样写代码:

<ol class="dp-c"><li class="alt"><span><span><span style=</span><span class="string">"color:#333333;font-family:''Helvetica, Arial, sans-serif'';"</span><span>></span><span class="keyword">if</span><span>(</span><span class="vars">$a</span><span> == true) </span><span class="vars">$a_count</span><span>++;</span> </span></span></li></ol>

这绝对WASTE.

写成:

<ol class="dp-c">
<li class="alt"><span><span><span style=</span><span class="string">"color:#333333;font-family:''Helvetica, Arial, sans-serif'';"</span><span>></span><span class="keyword">if</span><span>(</span><span class="vars">$a</span><span> == true)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$a_count</span><span>++;  </span>
</li>
<li><span>}</span> </span></li>
</ol>

不要尝试省略一些语法来缩短代码. 而是让你的逻辑简短.

>>使用有高亮语法显示的文本编辑器. 高亮语法能让你减少错误.

20. 使用array_map快速处理数组

比如说你想 trim 数组中的所有元素. 新手可能会:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">foreach</span><span>(</span><span class="vars">$arr</span><span> </span><span class="keyword">as</span><span> </span><span class="vars">$c</span><span> => </span><span class="vars">$v</span><span>)  </span></span></li>
<li><span>{  </span></li>
<li class="alt">
<span>    </span><span class="vars">$arr</span><span>[</span><span class="vars">$c</span><span>] = trim(</span><span class="vars">$v</span><span>);  </span>
</li>
<li><span>} </span></li>
</ol>

但使用 array_map 更简单:

<ol class="dp-c"><li class="alt"><span><span class="vars">$arr</span><span> = </span><span class="func">array_map</span><span>(</span><span class="string">'trim'</span><span> , </span><span class="vars">$arr</span><span>); </span></span></li></ol>

这会为$arr数组的每个元素都申请调用trim. 另一个类似的函数是 array_walk. 请查阅文档学习更多技巧.

21. 使用 php filter 验证数据

你肯定曾使用过正则表达式验证 email , ip地址等. 是的,每个人都这么使用. 现在, 我们想做不同的尝试, 称为filter.

php的filter扩展提供了简单的方式验证和检查输入.

22. 强制类型检查

<ol class="dp-c">
<li class="alt"><span><span class="vars">$amount</span><span> = </span><span class="func">intval</span><span>( </span><span class="vars">$_GET</span><span>[</span><span class="string">'amount'</span><span>] );  </span></span></li>
<li>
<span class="vars">$rate</span><span> = (int) </span><span class="vars">$_GET</span><span>[</span><span class="string">'rate'</span><span>]; </span>
</li>
</ol>

这是个好习惯.

23. 如果需要,使用profiler如xdebug

如果你使用php开发大型的应用, php承担了很多运算量, 速度会是一个很重要的指标. 使用profile帮助优化代码. 可使用

xdebug和webgrid.

24. 小心处理大数组

对于大的数组和字符串, 必须小心处理. 常见错误是发生数组拷贝导致内存溢出,抛出Fat

<ol class="dp-c">
<li class="alt"><span><span class="vars">$db_records_in_array_format</span><span>; </span><span class="comment">//This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB </span><span> </span></span></li>
<li><span> </span></li>
<li class="alt">
<span class="vars">$cc</span><span> = </span><span class="vars">$db_records_in_array_format</span><span>; </span><span class="comment">//2MB more </span><span> </span>
</li>
<li><span> </span></li>
<li class="alt">
<span>some_function(</span><span class="vars">$cc</span><span>); </span><span class="comment">//Another 2MB ?</span><span> </span>
</li>
</ol>

当导入或导出csv文件时, 常常会这么做.

不要认为上面的代码会经常因内存限制导致脚本崩溃. 对于小的变量是没问题的, 但处理大数组的时候就必须避免.

确保通过引用传递, 或存储在类变量中:

<ol class="dp-c">
<li class="alt"><span><span class="vars">$a</span><span> = get_large_array();  </span></span></li>
<li>
<span>pass_to_function(&</span><span class="vars">$a</span><span>); </span>
</li>
</ol>

这么做后,向函数传递变量引用(而不是拷贝数组). 查看

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445702.htmlTechArticle1.不要使用相对路径 常常会看到: require_once ( '../../lib/some_class.php' ); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录...
Statement:
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