1、不要使用相对路径
例如
require_once('../../lib/some_class.php');
该方法有很多缺点:
1)它首先查找指定的php包含路径, 然后查找当前目录
2)如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录
3)当定时任务运行该脚本, 它的上级目录可能就不是工作目录了
因此正确的写法是:
define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');
2、不要直接使用 require, include, include_once, required_once
require_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php');
这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件
function load_class($class_name)
{
$path = ROOT . '/lib/' . $class_name . '.php');
require_once( $path );
}
load_class('Database');
load_class('Mail');
有什么不一样吗? 该代码更具可读性,將来你可以按需扩展该函数,
function load_class($class_name)
{
$path = ROOT . '/lib/' . $class_name . '.php');
if(file_exists($path)){
include( $path );
}
}
还可做得更多:
1)为同样文件查找多个目录
2)能很容易的改变放置类文件的目录, 无须在代码各处一一修改
3)可使用类似的函数加载文件, 如html内容
不过强烈建议使用include、require 代替include_once ,require_once
3、使用可跨平台的函数执行命令
system, exec, passthru, shell_exec 这4个函数可用于执行系统命令. 每个的行为都有细微差别. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪个函数可用, 然而再使用它.
更好的方案是封成函数一个可跨平台的函数.
/**
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 this system';
$return_var = 1;
}
return array('output' => $output , 'status' => $return_var);
}
terminal('ls');
4、忽略php关闭标签
<?php
class super_class
{
function super_function()
{
}
}
//No closing tag
这会更好
5、在某地方收集所有输入, 一次输出给浏览器
这称为输出缓冲, 假如说你已在不同的函数输出内容:
function print_header()
{
echo "<div id='header'>Site Log and Login links</div>";
}
function print_footer()
{
echo "<div id='footer'>Site was made by me</div>";
}
print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
print_footer();
替代方案, 在某地方集中收集输出. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean. 如下:
function print_header()
{
$o = "<div id='header'>Site Log and Login links</div>";
return $o;
}
function print_footer()
{
$o = "<div id='footer'>Site was made by me</div>";
return $o;
}
echo print_header();
for($i = 0 ; $i < 100; $i++)
{
echo "I is : $i ';
}
echo print_footer();
为什么需要输出缓冲:
1)可以在发送给浏览器前更改输出. 如 str_replaces 函数或可能是 preg_replaces 或添加些监控/调试的html内容
2)输出给浏览器的同时又做php的处理很糟糕
6、为mysql连接设置正确的字符编码
//Attempt to connect to database
$c = mysqli_connect($this->host , $this->username, $this->password);
//Check connection validity
if (!$c)
{
die ("Could not connect to the database host: ". mysqli_connect_error());
}
//Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))
{
die('mysqli_set_charset() failed');
}
//一旦连接数据库, 最好设置连接的 characterset. 你的应用如果要支持多语言, 这么做是必须的
7、不要在应用中使用gzip压缩输出, 让apache处理
考虑过使用 ob_gzhandler 吗? 不要那样做. 毫无意义. php只应用来编写应用. 不应操心服务器和浏览器的数据传输优化问题、使用apache的mod_gzip/mod_deflate 模块压缩内容
8、写文件前, 检查目录写权限
$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、为函数内总具有相同值的变量定义成静态变量
//Delay for some time
function delay()
{
$sync_delay = get_option('sync_delay');
echo "Delaying for $sync_delay seconds...";
sleep($sync_delay);
echo "Done ";
}
用静态变量取代:
//Delay for some time
function 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、不要直接使用 $_SESSION 变量
$_SESSION['username'] = $username;
$username = $_SESSION['username'];
这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个session key. 例如, 一个前端门户, 和一个后台管理系统使用同一域名.
//从现在开始, 使用应用相关的key和一个包装函数:
define('APP_ID' , 'abc_corp_ecommerce');
//Function to get a session variable
function session_get($key)
{
$k = APP_ID . '.' . $key;
if(isset($_SESSION[$k]))
{
return $_SESSION[$k];
}
return false;
}
//Function set the session variable
function session_set($key , $value)
{
$k = APP_ID . '.' . $key;
$_SESSION[$k] = $value;
return true;
}
11、实用的写法
>>使用echo取代print
>>使用str_replace取代preg_replace, 除非你绝对需要
>>不要使用 short tag
>>简单字符串用单引号取代双引号
>>head重定向后记得使用exit
>>不要在循环中调用函数
>>isset比strlen快
>>始中如一的格式化代码
>>不要删除循环或者if-else的括号
>>不要尝试省略一些语法来缩短代码. 而是让你的逻辑简短
>>使用有高亮语法显示的文本编辑器. 高亮语法能让你减少错误
>>使用 php filter
>>验证数据强制类型检查
>>如果需要,使用profiler如xdebug
>>由始至终使用单一数据库连接
>>避免直接写SQL, 抽象之
>>在head中使用base标签
>>永远不要將 error_reporting 设为 0 eg:error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
12、使用array_map快速处理数组
$arr = array_map('trim' , $arr);
这会为$arr数组的每个元素都申请调用trim. 另一个类似的函数是 array_walk. 请查阅文档学习更多技巧
13、 避免使用全局变量
>>使用 defines/constants
>>使用函数获取值
>>使用类并通过$this访问
14、不要过分依赖 set_time_limit
注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下.因此, 就算数据库花费了很多时间查询, 脚本也不会停止执行. 视情况而定
参考原文地址:http://www.binarytides.com/40-techniques-to-enhance-your-php-code-part-2/