本文介绍一些关于改善和优化php代码的提示和技巧,供大家参考,具体内容如下
1.不要使用相对路径,要定义一个根路径
这样的代码行很常见:
require_once('../../lib/some_class.php');
这种方法有很多缺点:
1)、它首先搜索php包括路径中的指定目录,然后查看当前目录。因此,会检查许多目录。
2)、当一个脚本被包含在另一个脚本的不同目录中时,它的基本目录变为包含脚本的目录。
3)、另一个问题是,当一个脚本从cron运行时,它可能不会将它的父目录作为工作目录。
所以使用绝对路径便成为了一个好方法:
define('root' , '/var/www/project/');
require_once(root . '../../lib/some_class.php');
//rest of the code
这就是一个绝对路径,并且会一直保持不变。但是,我们可以进一步改善。目录/var/www/project可以变,那么我们每次都要改吗?
不,使用魔术常量如__file__可以让它变得可移植。请仔细看:
//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,包括require_once或include_once
你的脚本上可能会包括各种文件,如类库,实用程序文件和辅助函数等,就像这些:
require_once('lib/database.php');
require_once('lib/mail.php');
require_once('helpers/utitlity_functions.php');
这相当粗糙。代码需要更加灵活。写好辅助函数可以更容易地包含东西。举个例子:
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');
看到区别了吗?很明显。不需要任何更多的解释。
你还可以进一步改善:
function load_class($class_name)
{
//path to the class file
$path = root . '/lib/' . $class_name . '.php');
if(file_exists($path))
{
require_once( $path );
}
}
这样做可以完成很多事情:
为同一个类文件搜索多个目录。
轻松更改包含类文件的目录,而不破坏任何地方的代码。
使用类似的函数用于加载包含辅助函数、html内容等的文件。
3.在应用程序中维护调试环境
在开发过程中,我们echo数据库查询,转储创造问题的变量,然后一旦问题被解决,我们注释它们或删除它们。但让一切留在原地可提供长效帮助。
在开发计算机上,你可以这样做:
define('environment' , 'development');
if(! $db->query( $query )
{
if(environment == 'development')
{
echo "$query failed";
}
else
{
echo "database error. please contact administrator";
}
}
并且在服务器上,你可以这样做:
define('environment' , 'production');
if(! $db->query( $query )
{
if(environment == 'development')
{
echo "$query failed";
}
else
{
echo "database error. please contact administrator";
}
}
4.通过会话传播状态消息
状态消息是那些执行任务后生成的消息。
<?php
if($wrong_username || $wrong_password)
{
$msg = 'invalid username or password';
}
?>
<html>
<body>
<?php echo $msg; ?>
<form>
...
</form>
</body>
</html>
这样的代码很常见。使用变量来显示状态信息有一定的局限性。因为它们无法通过重定向发送(除非你将它们作为get变量传播给下一个脚本,但这非常愚蠢)。而且在大型脚本中可能会有多个消息等。
最好的办法是使用会话来传播(即使是在同一页面上)。想要这样做的话在每个页面上必须得有一个session_start。
function set_flash($msg)
{
$_session['message'] = $msg;
}
function get_flash()
{
$msg = $_session['message'];
unset($_session['message']);
return $msg;
}
在你的脚本中:
<?php
if($wrong_username || $wrong_password)
{
set_flash('invalid username or password');
}
?>
<html>
<body>
status is : <?php echo get_flash(); ?>
<form>
...
</form>
</body>
</html>
5.让函数变得灵活
function add_to_cart($item_id , $qty)
{
$_session['cart'][$item_id] = $qty;
}
add_to_cart( 'iphone3' , 2 );
当添加单一条目时,使用上面的函数。那么当添加多个条目时,就得创建另一个函数吗?no。只要让函数变得灵活起来使之能够接受不同的参数即可。请看:
function add_to_cart($item_id , $qty)
{
if(!is_array($item_id))
{
$_session['cart'][$item_id] = $qty;
}
else
{
foreach($item_id as $i_id => $qty)
{
$_session['cart'][$i_id] = $qty;
}
}
}
add_to_cart( 'iphone3' , 2 );
add_to_cart( array('iphone3' => 2 , 'ipad' => 5) );
好了,现在同样的函数就可以接受不同类型的输出了。以上代码可以应用到很多地方让你的代码更加灵活。
6.省略结束的php标签,如果它是脚本中的最后一行
我不知道为什么很多博客文章在谈论php小技巧时要省略这个技巧。
<?php
echo "hello";
//now dont close this tag
这可以帮助你省略大量问题。举一个例子:
类文件super_class.php
<?php
class super_class
{
function super_function()
{
//super code
}
}
?>
//super extra character after the closing tag
现在看index.php
require_once('super_class.php');
//echo an image or pdf , or set the cookies or session data
你会得到发送错误的header。为什么呢?因为“超级多余字符”,所有标题都去处理这个去了。于是你得开始调试。你可能需要浪费很多时间来寻找超级额外的空间。
因此要养成省略结束标签的习惯:
<?php
class super_class
{
function super_function()
{
//super code
}
}
//no closing tag
这样更好。
7.在一个地方收集所有输出,然后一次性输出给浏览器
这就是所谓的输出缓冲。比方说,你从不同的函数得到像这样的内容:
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 <br />';
}
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 <br />';
}
echo print_footer();
那么,为什么你应该做输出缓冲呢:
你可以在将输出发送给浏览器之前更改它,如果你需要的话。例如做一些str_replaces,或者preg_replaces,又或者是在末尾添加一些额外的html,例如profiler/debugger输出。
发送输出给浏览器,并在同一时间做php处理并不是好主意。你见过这样的网站,它有一个fatal error在侧边栏或在屏幕中间的方框中吗?你知道为什么会出现这种情况吗?因为处理过程和输出被混合在了一起。
8.当输出非html内容时,通过header发送正确的mime类型
请看一些xml。
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
$xml = "<response>
<code>0</code>
</response>";
//send xml data
echo $xml;
工作正常。但它需要一些改进。
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
$xml = "<response>
<code>0</code>
</response>";
//send xml data
header("content-type: text/xml");
echo $xml;
请注意header行。这行代码告诉浏览器这个内容是xml内容。因此,浏览器能够正确地处理它。许多javascript库也都依赖于header信息。
javascript,css,jpg图片,png图像也是一样:
javascript
header("content-type: application/x-javascript");
echo "var a = 10";
css
header("content-type: text/css");
echo "#div id { background:#000; }"
9.为mysql连接设置正确的字符编码
曾碰到过unicode/utf-8字符被正确地存储在mysql表的问题,phpmyadmin也显示它们是正确的,但是当你使用的时候,你的网页上却并不能正确地显示。里面的奥妙在于mysql连接校对。
$host = 'localhost';
$username = 'root';
$password = 'super_secret';
//attempt to connect to database
$c = mysqli_connect($host , $username, $password);
//check connection validity
if (!$c)
{
die ("could not connect to the database host: <br />". mysqli_connect_error());
}
//set the character set of the connection
if(!mysqli_set_charset ( $c , 'utf8' ))
{
die('mysqli_set_charset() failed');
}
一旦你连接到数据库,不妨设置连接字符集。当你在你的应用程序中使用多种语言时,这绝对有必要。
否则会发生什么呢?你会在非英文文本中看到很多的方框和????????。
10.使用带有正确字符集选项的htmlentities
php 5.4之前,使用的默认字符编码是iso-8859-1,这不能显示例如à â 这样的字符。
$value = htmlentities($this->value , ent_quotes , 'utf-8');
从php 5.4起,默认编码成了utf-8,这解决了大部分的问题,但你最好还是知道这件事,如果你的应用程序使用多种语言的话。
先介绍这10个技巧,剩下的php技巧我们将在接下来的文章中为大家分享,感谢您的阅读。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!