高质量PHP代码的50个实用技巧必备
文章主要为大家分享了50个高质量PHP代码的实用技巧,大家必备的php实用代码,感兴趣的小伙伴们可以参考一下。就跟随百分网小编一起去了解下吧,想了解更多相关信息请持续关注我们应届毕业生考试网!
1.不要使用相对路径
常常会看到:
?
1
require_once('../../lib/some_class.php');
该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录。因此会检查过多路径。如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.
另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了。因此最佳选择是使用绝对路径:
?
1
2
3
4
view sourceprint?
define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');
//rest of the code
我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:
?
1
2
3
4
5
//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
现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.
2. 不要直接使用 require, include, include_once, required_once
可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如:
?
1
2
3
require_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php');
这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:
?
1
2
3
4
5
6
7
8
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');
有什么不一样吗? 该代码更具可读性。將来你可以按需扩展该函数, 如:
?
1
2
3
4
5
6
7
8
9
function load_class($class_name)
{
//path to the class file
$path = ROOT . '/lib/' . $class_name . '.php');
if(file_exists($path))
{
require_once( $path );
}
}