[译]php 小提示

文章分类:PHP  查看次数:341 + 75

原文地址:click here

字符串

1、总是使用单引号,因为这会减少php 分析器的时间,自然也就提高了效率
2、当一个数组的变量是字符串时,用引号括起来

// OK

echo $row[$key];

// Wrong, unless key is a constant

echo $row[key];

// Right

echo $row['key'];

// OK, since it's in a string

echo "Text: $row[key]";

 

3、当有一大段html代码时,应该避免在php里echo,而是直接跳出php,用html代码来写。

我个人来说,很讨厌这样的代码

$something = 'this';
$something .= 'and this';
$something .= 'and this';
$something .= 'and this';
$something .= 'and this';
 

或者

$something = 'this'
. 'and this'
. 'and this'
. 'and this'
. 'and this'
. 'and this'
. 'and this';
 

我更喜欢下面这样

$something = 'this
and this
and this
and this';
 

为什么?因为前面两个例子里,php必须要调用内存分配给多个字符串,然后再将它门合并起来,为了增加可读性可以分行来书写

这里有一个小技巧,可以这样来写string,借鉴perl

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
 
使用","而不是"."

// Example:
echo 'foo', 'bar';
// translates to:
echo 'foo';
echo 'bar';

// whereas:
echo 'foo' . 'bar'
// translates to:
echo 'foobar'
 

前一个更有效,因为直接输出两个字符串,而后一个必须新生成一个字符串"foobar",然后再输出

考虑用str_replace替代preg_match或者ereg_match,除非必须使用正则

$string="The quick brown fox jumps over the lazy dog.";
$patterns[0] = "quick";
$patterns[1] = "brown";
$patterns[2] = "fox";

$replacements[0] = "slow";
$replacements[1] = "black";
$replacements[2] = "bear";

$string=str_replace($patterns, $replacements, $string);

//$string="The slow black bear jumps over the lazy dog."
 

ereg vs preg,选择preg*,因为preg大约比ereg快两倍,而且preg支持更多的正则
将换行符转换为XHTML


// the first bit is to make both "\r\n" and "\r" line endings into "\n"
$string = str_replace("\r\n", "\n", $string);
$string = str_replace("\r", "\n", $string);

// this next bit first adds an opening <p> then makes all double line breaks into </p><p>
$string = "<p>".str_replace("\n\n", "</p><p>", $string);

// finally this turns any single line breaks into
's and closes the last <p>
$string = str_replace("\n", "
", $string)."</p>";
 

MySQL

当把数据存入数据库时不要忘了mysql_escape_string(),这样可以避免注入

<?php
// Quote variable to make safe
function quote_smart($value)
{
   // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   if (!is_numeric($value)) {
       $value = "'" . mysql_real_escape_string($value) . "'";
   }
   return $value;
}

// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
   OR die(mysql_error());

// Make a safe query
$query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s",
           quote_smart($_POST['username']),
           quote_smart($_POST['password']));
mysql_query($query);
?>
 

不要在查询数据库的时候给数字加上引号,因为你不知道引号里面的数字,是否真的是数字

// If id is being passed in the URL
$id = (int) $_GET['id'];

$r = mysql_query("SELECT * FROM table WHERE id=$id");

 

这样即使id是abc,$id的值顶多也是0,所以不会带来任何的副作用。

列的字段和类型

应该选择最合适的字段,很多情况下,用不早INT,MEDIUMINT,SMALLINT,TYNYINT就足够了,这样可以节省时间和空间

将所有的列定义为NOT NULL,除非必须要使用NULL,同样NOT NULL 节省时间和空间

将INT的列设为UNSIGNED将会扩大数据范围,比如TINYINT的最大值是127. TINYINT UNSIGNED的最大值是255

SELECT author, title, description FROM content
 

SELECT * FROM content
 

更有效

其他

不要使用全局变量,如果register_globals 已被开启,可以通过下面这段小代码来模拟关闭

<?php
if (@ini_get('register_globals'))
foreach ($_REQUEST as $key => $value)
unset($GLOBALS[$key]);
?>
 
当运行for循环时,在外面定义循环次数

$array_count = count($_POST);

for ($i = '0'; $i < $array_count; $i++)
{
  $key = array_search('on', $_POST);
  echo $_POST[$key] . ' is on!';
}
 

格式化array输出

// debug - prints a nice formatted array, only need to pass it the name of the array
function print_format_array($array_name) {
  echo '<div style="padding:5px;border:1px solid #666666;margin-bottom:10px">';
  ksort($array_name);
  print_r($array_name);
  echo '</div>';
} // end func
 
让函数的名称变得更短

$fetch = 'mysql_fetch_assoc';
$arr = $fetch($result); // Will do the same as mysql_fetch_assoc
 
"&&"和"||"在某种程度上可以替代if

$z == 5 && print '$z is 5';
$z == 5 || print '$z is not 5';
get_error() && die('An error has occured!');
 
在一些大项目中,我喜欢模拟命名空间,以此来获得更好的API和可读性
nomarl

function getGbEntries()
{
...
}
function displayGbEntries($ary)
{
...
}

$rows = getGbEntries();
displayGbEntries($rows);
 

better

class GB
  function getEntries()
  {
    ..
  }
  function display($rows)
  {
    ..
  }
}
$rows = GB::getEntries();
GB::display($rows);
 

评论

发表评论