现在的位置: 首页 > 综合 > 正文

php提高代码质量36计

2013年08月14日 ⁄ 综合 ⁄ 共 1239字 ⁄ 字号 评论关闭

1.不要使用相对路径

常常会看到: 

  1. require_once('../../lib/some_class.php'); 

该方法有很多缺点:

它首先查找指定的php包含路径, 然后查找当前目录.

因此会检查过多路径.

如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.

另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了.

因此最佳选择是使用绝对路径:

  1. define('ROOT' , '/var/www/project/');  
  2. require_once(ROOT . '../../lib/some_class.php');  
  3.  
  4. //rest of the code 

我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如: 

  1. //suppose your script is /var/www/project/index.php  
  2. //Then __FILE__ will always have that full path.  
  3.  
  4. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));  
  5. require_once(ROOT . '../../lib/some_class.php');  
  6.  
  7. //rest of the code 

现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.

2. 不要直接使用 require, include, include_once, required_once

可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如: 

  1. require_once('lib/Database.php');  
  2. require_once('lib/Mail.php');  
  3.  
  4. require_once('helpers/utitlity_functions.php'); 

这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:

  1. function load_class($class_name)  
  2. {  
  3.     //path to the class file  
  4.     $path = ROOT . '/lib/' . $class_name . '.php');  
  5.     require_once$path );  
  6. }  
  7.  
  8. load_class('Database');  
  9. load_class('Mail'); 

有什么不一样吗? 该代码更具可读性.

將来你可以按需扩展该函数, 如:

  1. function load_class($class_name)  
  2. {  
  3.     //path to the class file  
  4.     $path = ROOT . '/lib/' . $class_name . '.php');  
  5.  
  6.     if(file_exists($path))  

抱歉!评论已关闭.